C++ STL Containers: map, set, unordered_map, queue and stack
The Standard Template Library (STL) gives you ready containers. You already know vector and array. Here are the others.
map: key and value, sorted
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> marks;
marks["Riya"] = 88;
marks["Aman"] = 72;
marks.insert({"Meera", 95});
std::cout << marks["Riya"] << ' ' << marks.at("Aman") << ' ' << marks.size() << '\n';
std::cout << marks.contains("Karan") << ' ' << marks.count("Meera") << '\n';
for (const auto& [name, m] : marks) { // sorted by key
std::cout << name << " = " << m << '\n';
}
}
Output
88 72 3
0 1
Aman = 72
Meera = 95
Riya = 88
Careful: marks["Karan"] on a missing key creates it with the value 0. Use find, contains or at to only look.
unordered_map: faster, no order
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> count;
for (std::string w : {"to", "be", "or", "not", "to", "be"}) {
count[w]++;
}
std::cout << count["to"] << ' ' << count["be"] << ' ' << count["or"] << '\n';
}
Output
2 2 1
set: unique values
#include <iostream>
#include <set>
int main() {
std::set<int> s = {5, 3, 9, 3, 1, 5};
s.insert(7);
for (int x : s) std::cout << x << ' '; // sorted and unique
std::cout << '\n' << s.contains(9) << ' ' << s.size() << '\n';
}
Output
1 3 5 7 9
1 5
stack, queue and deque
#include <deque>
#include <iostream>
#include <queue>
#include <stack>
int main() {
std::stack<int> st;
st.push(1); st.push(2); st.push(3);
std::cout << st.top() << '\n'; // last in, first out
st.pop();
std::cout << st.top() << '\n';
std::queue<std::string> q;
q.push("first"); q.push("second");
std::cout << q.front() << '\n'; // first in, first out
q.pop();
std::cout << q.front() << '\n';
std::deque<int> d = {2, 3};
d.push_front(1);
d.push_back(4);
for (int x : d) std::cout << x << ' ';
std::cout << '\n';
}
Output
3
2
first
second
1 2 3 4
Which container?
| Need | Use |
|---|---|
| A list which grows, fast reading by index | std::vector (the default) |
| Fixed size | std::array |
| Key and value, sorted | std::map |
| Key and value, fastest search | std::unordered_map |
| Unique values | std::set or std::unordered_set |
| Add and remove at both ends | std::deque |
| Stack, queue | std::stack, std::queue |
| Many inserts in the middle with stable iterators | std::list (rare) |
Note:
Start with vector and unordered_map. Change only when you measure a problem. Next: C++ Algorithms and Iterators.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |