vector (dynamic array), list (doubly linked list), map (key-value pairs, typically balanced-tree based), set (unique sorted elements), stack, queuesort(), find(), count()) that operate generically over containers via iterators#include <vector>
#include <algorithm>
vector<int> nums = {5, 2, 8, 1, 9};
sort(nums.begin(), nums.end()); // 1 2 5 8 9
| 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 |
Before STL, every C++ programmer wrote their own linked list, their own sort function, etc. — repetitive and error-prone. STL provides pre-built, well-tested, generic (template-based) versions of the data structures and algorithms used in almost every program.
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
vector<int> nums = {5, 2, 8, 1, 9}; // CONTAINER
sort(nums.begin(), nums.end()); // ALGORITHM, operating via ITERATORS (begin/end)
for (int n : nums) // range-based loop, uses iterators internally
cout << n << " "; // 1 2 5 8 9
auto it = find(nums.begin(), nums.end(), 8); // ALGORITHM again
if (it != nums.end())
cout << "\nFound 8 at position " << (it - nums.begin()); // position 3
return 0;
}
#include <map>
map<string, int> ages;
ages["Ali"] = 25;
ages["Sara"] = 30;
cout << ages["Ali"]; // 25
for (auto& pair : ages)
cout << pair.first << ": " << pair.second << endl; // iterates in sorted key order
An iterator behaves like a pointer (*it dereferences, ++it advances) but works uniformly across very different containers (vector, list, map...). This is why sort(nums.begin(), nums.end()) can work on a vector while the same style of call works on other containers too — the algorithm doesn't need to know the container's internal structure, only how to move an iterator.
sort() operate generically over containers using: