이 튜토리얼에서는 선거 승자를 찾는 프로그램을 작성할 것입니다. 선거에서 각 후보자가 얻은 표가 있을 것입니다. 예를 들어 보겠습니다.
입력
{"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A", "C", "D"} 출력
A
여기 A 및 B 같은 수의 표를 얻었습니다. 이 경우 이름의 알파벳 순서에 따라 우승자를 선택해야 합니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
더미 데이터로 문자열 배열을 초기화합니다.
-
문자열을 키로 사용하여 지도 초기화 및 int를 값으로 .
-
투표 배열을 반복하고 각 구성원의 투표 수를 계산합니다. 지도를 사용하여 투표 수를 저장합니다.
-
우리는 투표수를 가지고 있습니다. 선거 승자를 찾으려면 지도를 반복하고 최대 표를 받은 키를 찾으세요.
-
두 회원이 같은 표를 얻었다면 이름을 확인하세요.
-
승자를 인쇄하십시오.
예시
코드를 봅시다.
#include "bits/stdc++.h"
using namespace std;
void findElectionWinner(string votes[], int total_votes) {
map<string, int> candidate_votes_count;
// counting each person votes
for (int i = 0; i < total_votes; i++) {
candidate_votes_count[votes[i]]++;
}
// finding winner
int max_votes = 0;
string election_winner;
for (auto& entry : candidate_votes_count) {
string key = entry.first;
int val = entry.second;
// checking the votes with max votes
if (val > max_votes) {
// updating max votes and member
max_votes = val;
election_winner = key;
// comparing the name if the votes are equal
}
else if (val == max_votes && election_winner > key) {
election_winner = key;
}
}
cout << election_winner << endl;
}
int main() {
string votes[] = {"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A"};
findElectionWinner(votes, 13);
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
A
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.