Find winner of an election where votes are represented as candidate names | C ++ ++ program to find winner in an election . ; 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 . ; Insert all votes in a hashmap ; Traverse through map to find the candidate with maximum votes . ; If there is a tie , pick lexicographically smaller . ; Driver code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; void findWinner ( vector < string > & votes ) { unordered_map < string , int > mapObj ; for ( auto & str : votes ) { mapObj [ str ] ++ ; } int maxValueInMap = 0 ; string winner ; for ( auto & entry : mapObj ) { string key = entry . first ; int val = entry . second ; if ( val > maxValueInMap ) { maxValueInMap = val ; winner = key ; } else if ( val == maxValueInMap && winner > key ) winner = key ; } cout << winner << endl ; } int main ( ) { vector < string > votes = { " john " , " johnny " , " jackie " , " johnny " , " john " , " jackie " , " jamie " , " jamie " , " john " , " johnny " , " jamie " , " johnny " , " john " } ; findWinner ( votes ) ; return 0 ; }