C++
Counting With std::map in C++: Tallying a Club Election Without Mixing Up the Votes
Introduction
"Count how many times each thing appears" is one of the most common jobs a program does: votes per candidate, orders per product, errors per page, words in a text. With only arrays or vectors, you end up keeping two lists side by side, one of names and one of counts, and keeping them in step by hand. That works until someone changes one list and forgets the other, and then every count is attached to the wrong name.
In this tutorial we will count the votes of a sports club's committee election. We will start with two parallel vectors and watch a single line of sorting hand the election to the wrong person. Then we will replace both vectors with one std::map, learn the one behaviour of its [] operator that surprises everyone, reject ballots for people who are not standing, and declare a winner, or a tie.
I will assume you are working in the C/C++ sandbox on Bytestark, in /home/coder/learning, and that you know basic C++: variables, if, loops, std::string and std::vector. No previous experience with maps is needed.
Background
A std::map stores key–value pairs. Each key appears at most once, and each key has exactly one value attached to it. In std::map<std::string, int> votes;, the keys are names (std::string) and the values are vote counts (int). You get the map type by including the <map> header.
Three properties of std::map matter in this tutorial:
- Keys are unique. Storing a value under a key that already exists replaces or updates that key's value; it never creates a second entry.
- Keys are kept sorted. However you insert them, a loop over the map visits the keys in ascending order, which for strings means alphabetical order by character code.
- The value travels with its key. A key and its value are stored together as one element, so they cannot drift apart the way two separate vectors can.
You will see two more words. An iterator is an object that refers to one element of a container, a bit like a bookmark; for a map, it refers to a key–value pair. Every container also has an end() iterator that refers to the position just past the last element, and functions that search a container return end() to say "not found".
Practical Scenario
A local rowing club elects its committee chair once a year. Members write a name on a paper ballot, and the secretary types the ballots into a program that prints the result. This year Ana, Lena, Mira and Tomas are standing. Bogdan was nominated but withdrew a week before the vote.
The result is announced at the general meeting and goes into the minutes, so it has to be right the first time. A count attached to the wrong name announces the wrong chair. A withdrawn candidate who appears in the results with zero votes starts an argument about whether he was still standing. A ballot with a misspelled name must be counted as spoiled, not quietly ignored and not quietly given to someone. And if two candidates draw, the club's rules require a second round, not an arbitrary winner.
We will start with the ten valid ballots that the secretary has typed in so far, and add the problematic ones as we go.
The Problem
Here is the counter as the secretary first wrote it. It keeps one vector of names and one of counts. For each ballot, it searches the names; if the name is there, it increases the count at the same position, and if not, it adds the name with a count of 1. Before printing, it sorts the names so the results are alphabetical.
Create the file:
touch election.cpp
Put this in it:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> ballots = {
"Tomas", "Mira", "Ana", "Ana", "Mira",
"Ana", "Tomas", "Ana", "Mira", "Ana"
};
std::vector<std::string> names;
std::vector<int> counts;
for (const std::string& ballot : ballots) {
bool found = false;
for (std::size_t i = 0; i < names.size(); i++) {
if (names[i] == ballot) {
counts[i]++;
found = true;
}
}
if (!found) {
names.push_back(ballot);
counts.push_back(1);
}
}
std::sort(names.begin(), names.end());
for (std::size_t i = 0; i < names.size(); i++) {
std::cout << names[i] << ": " << counts[i] << "\n";
}
return 0;
}
Build it and run it:
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
Ana: 2
Mira: 3
Tomas: 5
Count the ballots yourself: Ana appears five times, Mira three times, Tomas twice. The program says Tomas has five votes. It has just elected the candidate who came last.
The counting part is correct. for (const std::string& ballot : ballots) visits each ballot in turn; the inner loop looks for it in names, and the position i where it is found is the position whose count is increased. After the loop, names is Tomas, Mira, Ana in the order they first appeared, and counts is 2, 3, 5. Name and count belong together only because they sit at the same index in two different vectors.
Then std::sort(names.begin(), names.end()) sorts the names into Ana, Mira, Tomas. It sorts names and nothing else, because it has no idea that counts exists. So counts is still 2, 3, 5, and printing index by index pairs Ana with 2 and Tomas with 5. One innocent line for nicer output broke the link between every name and its count, and the compiler had nothing to complain about.
One Map Instead of Two Vectors
The problem is that the pairing of name and count lives only in our heads, as "same index". A std::map makes the pairing part of the data: each element is a name and its count, stored together. Replace the whole of election.cpp with:
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> ballots = {
"Tomas", "Mira", "Ana", "Ana", "Mira",
"Ana", "Tomas", "Ana", "Mira", "Ana"
};
std::map<std::string, int> votes;
for (const std::string& ballot : ballots) {
++votes[ballot];
}
for (const auto& [name, count] : votes) {
std::cout << name << ": " << count << "\n";
}
return 0;
}
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
Ana: 5
Mira: 3
Tomas: 2
Ana has five votes, as she should, and the results are in alphabetical order without any call to std::sort. The whole search-or-insert loop became one line. Let's see why that line is enough.
std::map<std::string, int> votes; creates an empty map whose keys are strings and whose values are integers.
++votes[ballot]; does all the counting, and it relies on what [] does on a map. votes[ballot] looks for the key ballot:
- If the key is already in the map, it gives you that key's value, the actual
intstored inside the map, not a copy. - If the key is not in the map, it first inserts it with a default value, which for an
intis 0, and then gives you that new value.
Either way you get the count stored in the map, and ++ increases it in place. The first ballot for Tomas inserts Tomas with 0 and makes it 1; the second finds Tomas and makes it 2. That is the same logic as the two vectors, except that the map does the searching and the inserting, and it cannot attach a count to the wrong name.
The order comes for free because a std::map keeps its keys sorted at all times. Each insert puts the new key in its sorted place, so a loop over the map always visits Ana, Mira, Tomas, whatever order the ballots came in.
for (const auto& [name, count] : votes) is the loop over the map, and it has two parts worth taking apart.
- Each element of a
std::map<std::string, int>is a pair: a key and its value. Its exact type isstd::pair<const std::string, int>, andautoasks the compiler to work that out for us.const auto&means we look at each element through a reference, so nothing is copied, andconst, so the loop cannot change anything by accident. [name, count]is a structured binding, available since C++17, which is why we compile with-std=c++17. It unpacks the pair into two names:namefor the key andcountfor the value. Without it, you would writeentry.firstandentry.second, which work just as well but say less about what the values mean.
Try it: Add one more ballot, "ana" with a lowercase a, to the end of the list and rebuild. Predict where it appears in the output. You get a fourth line, ana: 1, after Tomas: to the map, "ana" and "Ana" are different keys, and sorting by character code puts every lowercase letter after every uppercase one. Then change ++votes[ballot]; to votes[ballot] = 1; and run again: every candidate shows 1, because assignment replaces the value instead of adding to it. Undo both changes.
Looking Up a Name Without Adding It
At the meeting, someone asks how many votes Bogdan got, since his name was printed on some ballots before he withdrew. The secretary adds one line before the results loop:
std::cout << "Bogdan got " << votes["Bogdan"] << " votes\n";
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
Bogdan got 0 votes
Ana: 5
Bogdan: 0
Mira: 3
Tomas: 2
The question was answered correctly: 0. But look at the results below it. Bogdan is now listed as a candidate. The lookup answered the question by adding him to the map, which is exactly what [] does with a missing key: it inserted Bogdan with the default value 0 and returned that 0. The results loop then printed every key in the map, including the new one. A withdrawn candidate is now in the official results. Asking a question changed the answer.
The usual way to make such a mistake impossible is to put the lookup in a function that receives the map as const, meaning the function promises not to change it. Add this function above main:
int votes_for(const std::map<std::string, int>& votes, const std::string& name) {
return votes[name];
}
And change the Bogdan line in main to use it:
std::cout << "Bogdan got " << votes_for(votes, "Bogdan") << " votes\n";
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
election.cpp: In function ‘int votes_for(const std::map<std::__cxx11::basic_string<char>, int>&, const std::string&)’:
election.cpp:7:22: error: passing ‘const std::map<std::__cxx11::basic_string<char>, int>’ as ‘this’ argument discards qualifiers [-fpermissive]
7 | return votes[name];
| ^
In file included from /usr/include/c++/13/map:63,
from election.cpp:2:
/usr/include/c++/13/bits/stl_map.h:504:7: note: in call to ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; mapped_type = int; key_type = std::__cxx11::basic_string<char>]’
504 | operator[](const key_type& __k)
| ^~~~~~~~
The compiler refuses, and this long message is worth reading once, because you will meet its shape again. Ignore the template noise and look for three things.
- The location:
election.cpp:7:22, thereturn votes[name];line. - The complaint:
passing ‘const std::map<...>’ as ‘this’ argument discards qualifiers.thisis the object a member function is called on, herevotes. "Discards qualifiers" means the call would drop theconst: we are calling a function that is allowed to modify the map, on a map we promised not to modify. - The note:
in call to ‘... operator[](const key_type&)’. The function in question isoperator[], the[]we used. Its declaration in the library header has noconstat the end, which marks it as a function that may change the map.
In other words, the compiler knows what we just found out by accident: [] on a map can insert, so it is simply not available on a const map. The std::__cxx11::basic_string<char> you see everywhere is just the full internal name of std::string.
To look up a key without ever inserting it, we use find. Replace the body of votes_for:
int votes_for(const std::map<std::string, int>& votes, const std::string& name) {
auto it = votes.find(name);
if (it == votes.end()) {
return 0;
}
return it->second;
}
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
Bogdan got 0 votes
Ana: 5
Mira: 3
Tomas: 2
The answer is still 0, and Bogdan is no longer in the results. Here is how find works.
votes.find(name)searches for the key and returns an iterator. If the key exists, the iterator refers to its element. If not, it is equal tovotes.end(), the "one past the last element" position that means "not found".findnever inserts anything, which is why it is allowed on aconstmap.if (it == votes.end())is the not-found test. Here we answer 0, because "no ballots for Bogdan" really does mean zero votes.it->secondreads the value of the element the iterator refers to. An iterator works like a pointer to the pair, and->reaches a member through it:it->firstwould be the name,it->secondis the count.
Try it: Replace the whole body of votes_for with return votes.at(name); and rebuild. at is allowed on a const map, so it compiles. Predict what happens for Bogdan. The program stops with terminate called after throwing an instance of 'std::out_of_range', what(): map::at, and the terminal prints Aborted. at never inserts either; for a missing key it throws an exception, and since nothing catches it, the program ends. Use at when a missing key is a bug, and find when it is a normal answer. Put the find version back.
Rejecting Ballots for People Who Are Not Standing
The secretary has typed in the last two ballots. One says tomas, in lowercase. The other says Bogdan. With ++votes[ballot], both would be counted: tomas as a new fifth candidate and Bogdan as a candidate with one vote. The club's rule is that a ballot naming anyone who is not on the official list is spoiled.
So the map should start with exactly the official candidates, each at 0, and a ballot should only be counted if its name is already a key. Replace the whole of election.cpp with:
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
const std::vector<std::string> candidates = {"Ana", "Lena", "Mira", "Tomas"};
std::vector<std::string> ballots = {
"Tomas", "Mira", "Ana", "Ana", "Mira",
"Ana", "Tomas", "Ana", "Mira", "Ana",
"tomas", "Bogdan"
};
std::map<std::string, int> votes;
for (const std::string& name : candidates) {
votes[name] = 0;
}
int spoiled = 0;
for (const std::string& ballot : ballots) {
auto it = votes.find(ballot);
if (it == votes.end()) {
std::cout << "spoiled ballot: \"" << ballot << "\"\n";
++spoiled;
continue;
}
++it->second;
}
for (const auto& [name, count] : votes) {
std::cout << name << ": " << count << "\n";
}
std::cout << "spoiled: " << spoiled << "\n";
return 0;
}
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
spoiled ballot: "tomas"
spoiled ballot: "Bogdan"
Ana: 5
Lena: 0
Mira: 3
Tomas: 2
spoiled: 2
Both bad ballots are reported and counted as spoiled, the four official candidates are in the results, and Lena appears with 0 votes, which is correct: she was standing and nobody voted for her. This version no longer has the votes_for function, because the results now list every official candidate, with zero where nobody voted for them.
There are two loops, and they use the map in two different ways on purpose.
The first loop builds the official list:
for (const std::string& name : candidates) {
votes[name] = 0;
}
Here inserting is exactly what we want, so [] is the right tool: votes[name] creates each candidate's entry, and = 0 sets it. After this loop the map holds four keys and no others. This is also why Lena shows up in the results. In the earlier versions, a candidate only existed once someone voted for them.
The second loop counts the ballots:
auto it = votes.find(ballot);
if (it == votes.end()) {
std::cout << "spoiled ballot: \"" << ballot << "\"\n";
++spoiled;
continue;
}
++it->second;
Here inserting would be a bug, so we use find. A name that is not a key is not a candidate, so the ballot is reported, counted as spoiled, and continue moves on to the next ballot. For a valid name, ++it->second increases the count through the iterator find already gave us. We could write ++votes[ballot] instead, since we know the key exists, but that would search the map a second time for something we have just found.
Inside the message, \" is an escaped double quote. We print quotes around the name so that a ballot with a stray space, such as "Mira ", would be visible as such.
Try it: Delete the first loop, the three lines that set each candidate to 0, and rebuild. Predict how many ballots are spoiled and which candidates are listed. All 12 ballots are reported as spoiled and no candidate is listed at all: the map starts empty, so find never finds anyone. The map is now the official candidate list, so it has to be filled before counting. Put the loop back.
Declaring the Winner, or a Tie
The last step is the announcement. We need the candidate with the most votes, and we must notice if two or more candidates share the highest count, because the rules then call for a second round. Add this block at the end of main, after the spoiled line and before return 0;:
std::string winner;
int best = -1;
bool tie = false;
for (const auto& [name, count] : votes) {
if (count > best) {
best = count;
winner = name;
tie = false;
} else if (count == best) {
tie = true;
}
}
if (tie) {
std::cout << "result: tie at " << best << " votes, a second round is needed\n";
} else {
std::cout << "result: " << winner << " wins with " << best << " votes\n";
}
g++ -std=c++17 -Wall -Wextra -o election election.cpp && ./election
spoiled ballot: "tomas"
spoiled ballot: "Bogdan"
Ana: 5
Lena: 0
Mira: 3
Tomas: 2
spoiled: 2
result: Ana wins with 5 votes
Ana wins with five votes. The loop is a "find the largest" search with one addition, the tie flag, so let's trace it on the real data. The map is visited in key order.
beststarts at -1, lower than any real count, so the first candidate always becomes the leader.Ana: 5: 5 is more than -1, so Ana leads with 5, andtieis set tofalse.Lena: 0: less than 5, neither branch runs.Mira: 3andTomas: 2: also less than 5, nothing changes.
The loop ends with winner as Ana, best as 5 and tie false.
The two branches of the if are what make ties work. When a count equals the current best, else if (count == best) records a tie. When a later count beats the best, the first branch takes over and resets tie to false, because a tie between two candidates who have now both been overtaken no longer matters. Only a tie at the very top survives to the end of the loop.
Try it: Add two more "Mira" ballots to the list and rebuild. Predict the result line. Mira now has 5 votes like Ana, and you get result: tie at 5 votes, a second round is needed. Then delete the else if branch and its body, leaving the } that closes the first if, and run again: the program announces Ana wins with 5 votes. Without the tie check, the "winner" of a draw is simply whoever comes first alphabetically, because that is the order the map is visited in. Put the branch back.
Summary
We built a vote counter for a club election that cannot attach a count to the wrong name, lists the official candidates in alphabetical order, keeps withdrawn and misspelled names out of the results, and calls a tie a tie. We kept the ballots in the program to focus on the map itself. Reading them from a file, and accepting tomas as a vote for Tomas by normalising case, are natural extensions that we deliberately left out.
- Two parallel vectors keep keys and values together only by index, and any operation on one vector alone, such as sorting it, silently breaks every pairing.
- A
std::map<Key, Value>stores each key with its value as one element, keeps keys unique, and keeps them sorted, so iterating it visits keys in ascending order. map[key]returns a reference to the key's value and inserts the key with a default value (0 forint) if it is missing, which makes++counts[key]a complete counting loop.- Because
[]can insert, reading a key with it adds that key to the map, and[]is not available on aconstmap at all. - Use
findto look up without inserting: it returns an iterator to the element, orend()when the key is absent, andit->secondreads the value. at(key)also never inserts, but throwsstd::out_of_rangefor a missing key; use it when a missing key means a bug.- To accept only known keys, fill the map with them first and treat a failed
findas invalid input. - When looking for a maximum, track ties explicitly; otherwise a draw is decided by iteration order, which for a map is alphabetical.