在C++中查詢選舉獲勝者(投票以候選人姓名錶示)


在本教程中,我們將編寫一個程式來查詢選舉獲勝者。我們將有一個數組,其中包含每個候選人在選舉中獲得的票數。讓我們來看一個例子。

輸入 

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

輸出 

A

這裡,AB獲得的票數相同。在這種情況下,我們必須根據他們姓名的字母順序來選擇獲勝者。

讓我們看看解決這個問題的步驟。

  • 用虛擬資料初始化一個字串陣列。

  • 初始化一個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

結論

如果您對本教程有任何疑問,請在評論區提出。

更新於:2020年12月29日

671 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.