Module 22: STL – Standard Template LibraryIntermediate50 min read
Associative & Unordered Containers (set, map, unordered_map) & STL Algorithms
Compare O(log n) ordered map/set vs O(1) avg unordered_map/unordered_set, and use sort, binary_search, lower_bound, accumulate, and pair/tuple.
Key Takeaways & Core Concepts
- Utilities:
std::pair,std::tuple, and C++17 structured bindingsauto [k, v] = ....
1. Ordered (`map` / `set`) vs. Unordered (`unordered_map` / `unordered_set`)
| Container | Backing Structure | Lookup / Insert | Key Ordering |
|---|---|---|---|
| `std::map` / `set` | Red-Black Tree | O(log n) | Sorted ascending |
| `std::unordered_map` / `set` | Hash Table | O(1) avg, O(n) worst | Unordered |
1. lower_bound, upper_bound & map Frequency
1#include <iostream>
2#include <vector>
3#include <algorithm>
4#include <map>
5
6int main() {
7 std::vector<int> v = {10, 20, 20, 20, 30, 40};
8 auto lo = std::lower_bound(v.begin(), v.end(), 20) - v.begin();
9 auto hi = std::upper_bound(v.begin(), v.end(), 20) - v.begin();
10 std::cout << "Count of 20: " << (hi - lo) << "\n";
11
12 std::map<std::string, int> scores = {{"Alice", 95}, {"Bob", 88}};
13 for (const auto& [name, sc] : scores) std::cout << name << "=" << sc << " ";
14 return 0;
15}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
15 lines
Note: `upper_bound - lower_bound` counts occurrences in O(log n) time.
2. Essential `<algorithm>` & `<numeric>` Functions
std::sort(O(n log n)),std::stable_sortstd::binary_search,std::lower_bound(first>=x),std::upper_bound(first>x)std::accumulate,std::transform,std::unique,std::next_permutation- Utilities:
std::pair,std::tuple, and C++17 structured bindingsauto [k, v] = ....
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)