ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมเพื่อค้นหาผู้ชนะการเลือกตั้ง เราจะมีคะแนนเสียงมากมายที่ผู้สมัครแต่ละคนได้รับในการเลือกตั้ง มาดูตัวอย่างกัน
ป้อนข้อมูล
{"A", "B", "C", "B", "A", "C", "D", "D", "A", "B", "D", "B", "A", "C", "D"} ผลผลิต
A
ที่นี่ A และ ข ได้คะแนนเสียงเท่ากัน ในกรณีนั้น เราต้องเลือกผู้ชนะตามลำดับตัวอักษรของชื่อของพวกเขา
มาดูขั้นตอนการแก้ปัญหากัน
-
เริ่มต้นอาร์เรย์ของสตริงด้วยข้อมูลจำลอง
-
เริ่มต้นแผนที่ด้วยสตริงเป็น คีย์ และ 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
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น