Lesson 6 of 13
STL Containers
Learn the Standard Template 's main containers and , so you can use ready-made vectors, maps and instead of writing your own.
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
// vector — dynamic array
vector<int> v = {5, 2, 8, 1, 9, 3};
sort(v.begin(), v.end());
cout << "Sorted: ";
for (int n : v) cout << n << " ";
cout << "
"; // 1 2 3 5 8 9
int total = accumulate(v.begin(), v.end(), 0);
cout << "Sum: " << total << "
"; // 28
auto it = find(v.begin(), v.end(), 5);
cout << "5 found: " << (it != v.end()) << "
"; // 1 (true)
// map — sorted key-value pairs
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Carol"] = 92;
for (const auto& [name, score] : scores) {
cout << name << ": " << score << "
"; // alphabetical order
}
// unordered_map — hash table, O(1) lookup, no order
unordered_map<string, int> fast_scores = {
{"Alice", 95}, {"Bob", 87}
};
// set — sorted unique elements
set<int> unique = {5, 3, 1, 4, 1, 5, 9, 2, 6}; // duplicates removed
cout << "Set: ";
for (int n : unique) cout << n << " "; // 1 2 3 4 5 6 9
cout << "
";
return 0;
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.