在C++中查找选举获胜者(投票以候选人姓名表示)
在本教程中,我们将编写一个程序来查找选举获胜者。我们将有一个数组,其中包含每个候选人在选举中获得的票数。让我们来看一个例子。
输入
{"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A", "C", "D"}输出
A
这里,A和B获得的票数相同。在这种情况下,我们必须根据他们姓名的字母顺序来选择获胜者。
让我们看看解决这个问题的步骤。
用虚拟数据初始化一个字符串数组。
初始化一个map,其中字符串作为键,整数作为值。
遍历votes数组并计算每个成员的票数。使用map存储票数。
我们已经获得了票数。为了找到选举获胜者,请遍历map并找到票数最多的键。
如果两个人获得相同数量的票数,则检查他们的姓名。
打印获胜者。
示例
让我们看看代码。
#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
结论
如果您对本教程有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP