optional · CSS study notes
Standard Template Library (extended)
- A C++ library providing generic, reusable data structures and algorithms
- Containers:
vector(dynamic array),list(doubly linked list),map(key-value pairs, typically balanced-tree based),set(unique sorted elements),stack,queue - Iterators: generalized pointers used to traverse container elements uniformly
- Algorithms: pre-built functions (e.g.,
sort(),find(),count()) that operate generically over containers via iterators
Worked Example — vector, iterator, and sort() together
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> nums = {5, 2, 8, 1, 9};
sort(nums.begin(), nums.end()); // algorithm operating via iterators
for (auto it = nums.begin(); it != nums.end(); ++it) // iterator traversal
cout << *it << " ";
cout << endl;
return 0;
}
Output: 1 2 5 8 9
When to use which container (quick reference)
| Need | Container |
|---|---|
| Fast random access, dynamic size | vector |
| Frequent insert/delete in the middle | list |
| Key-value lookup, sorted keys | map |
| Unique elements, sorted | set |
| LIFO access | stack |
| FIFO access | queue |
Self-Test Questions
- What does an iterator generalize, and why is that useful for writing algorithms like
sort()? - When would
listbe preferred overvector?