首页 > 解决方案 > 按字典顺序选择更小的

问题描述

问题:https ://www.geeksforgeeks.org/find-winner-election-votes-represented-candidate-names/

给定选举中的候选人姓名数组。数组中的候选人名称代表对该候选人的投票。打印获得最大票数的候选人姓名。如果有平局,则按字典顺序打印较小的名称。

// C++++ program to find winner in an election. 
#include "bits/stdc++.h" 
using namespace std; 

/* We have four Candidates with name as 'John', 
'Johnny', 'jamie', 'jackie'. 
The votes in String array are as per the 
votes casted. Print the name of candidates 
received Max vote. */
void findWinner(vector<string>& votes) 
{ 
    
    // Insert all votes in a hashmap 
    map<string,int> mapObj ; 
    for (auto& str : votes) 
    { 
        mapObj[str]++; 
    } 

    // Traverse through map to find the candidate 
    // with maximum votes. 
    int maxValueInMap = 0; 
    string winner; 
    for (auto& entry : mapObj) 
    { 
        string key = entry.first; 
        int val = entry.second; 
        if (val > maxValueInMap) 
        { 
            maxValueInMap = val; 
            winner = key; 
        } 

        // If there is a tie, pick lexicographically 
        // smaller. 
        else if (val == maxValueInMap && 
            winner>key) 
            winner = key; 
    } 
    cout << winner << endl; 
} 

// Driver code 
int main() 
{ 
vector<string> votes = { "john", "johnny", "jackie", 
                    "johnny", "john", "jackie", 
                    "jamie", "jamie", "john", 
                    "johnny", "jamie", "johnny", 
                    "john" }; 

findWinner(votes); 
return 0; 
} 

这是如何选择字典顺序较小的键?我无法清楚地理解这部分代码

else if (val == maxValueInMap && 
            winner>key) 
            winner = key; 

有人可以帮我弄这个吗?谢谢!

标签: c++stl

解决方案


winner>key是一个字典比较。如果按key字典顺序小于winner(我确实认为以相反的方式编写它会更容易混淆key<winner),这是真的。

所以代码是说,如果刚刚找到的分数等于迄今为止找到的最佳分数,并且如果刚刚找到的候选人在字典上小于目前的获胜候选人,则选择新的候选人。所以这似乎是必要的。


推荐阅读