查找以C ++形式将选票表示为候选人姓名的选举的获胜者

在本教程中,我们将编写一个找到选举获胜者的程序。我们将有每个候选人在选举中获得的一系列投票。让我们来看一个例子。

输入 

{"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A", "C", "D"}

输出 

A

在这里,AB的票数相同。在这种情况下,我们必须根据姓名的字母顺序选择获奖者。

让我们看看解决问题的步骤。

  • 用伪数据初始化字符串数组。

  • 使用string作为和int作为value初始化映射。

  • 遍历投票数组并计算每个成员的投票数。使用映射存储票数。

  • 我们有票数。要找到选举获胜者,请遍历映射并找到具有最高投票数的钥匙。

  • 如果两个成员的票数相同,则检查其姓名。

  • 打印获胜者。

示例

让我们看一下代码。

#include "bits/stdc++.h"
using namespace std;
void findElectionWinner(string votes[], int total_votes) {
   map<string, int> candidate_votes_count;
   // 数每个人的票
   for (int i = 0; i < total_votes; i++) {
      candidate_votes_count[votes[i]]++;
   }
   // 寻找胜利者
   int max_votes = 0;
   string election_winner;
   for (auto& entry : candidate_votes_count) {
      string key = entry.first;
      int val = entry.second;
      // 以最高票数检查票数
      if (val > max_votes) {
         // 更新最高投票数和成员
         max_votes = val;
         election_winner = key;
         // 如果票数相等,则比较姓名
      }
      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

结论