The STL is three things that fit together: containers that store data, iterators that address positions in them, and algorithms that operate on ranges of iterators. Because algorithms talk to iterators rather than containers, std::sort works on a vector, an array or a deque without knowing which it has.
Sequential containers keep elements in the order you put them. std::vector is the default and should be your first thought for almost everything: a contiguous dynamic array, index access in constant time, appending amortised constant, and - the part people underestimate - laid out contiguously in memory, so iterating one is as cache-friendly as data gets. Inserting in the middle is linear because everything after shifts. std::list is a doubly-linked list with constant-time insertion anywhere you already have an iterator, at the price of no indexing and a cache miss per node. Measure before choosing it; the obvious theory is wrong more often than not. std::deque allows fast insertion at both ends.
Associative containers store by key. std::map keeps keys sorted in a balanced tree, giving ordered iteration and O(log n) lookup. std::unordered_map is a hash table with average O(1) lookup and no order at all. If you do not need keys in order, the unordered version is usually faster. std::set and std::unordered_set are the same two shapes for keys with no value attached.
Iterators generalise the pointer. begin() gives one for the first element, end() gives one past the last - a position, not an element, which is why end() is never dereferenced and why if (it != container.end()) is how you test a search result. Half-open ranges like this are what make end() - begin() the size and empty ranges representable.
Algorithms live in <algorithm> and <numeric>. std::sort, std::find, std::reverse, std::count_if, std::accumulate, std::transform. A standard algorithm is better than a handwritten loop for three reasons: it is correct, it is probably faster than yours, and the name says what you meant where a for loop needs reading. C++20 adds a std::ranges version of each that takes the container directly, which removes the begin(), end() pair from every call.
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <set>
#include <algorithm>
#include <numeric>
#include <string>
int main()
{
// ---------------- Sequential ----------------
std::vector<int> v{40, 10, 30, 20};
v.push_back(50); // amortised O(1) at the end
v.insert(v.begin(), 5); // O(n) at the front - everything shifts
std::cout << v[0] << '\n'; // 5 - no bounds check
std::cout << v.at(99) << '\n'; // throws std::out_of_range
std::cout << v.size() << '\n';
std::cout << v.capacity() << '\n'; // >= size. Growth is amortised.
v.reserve(1000); // one allocation instead of ~10 reallocations
// if you know roughly how many are coming
// ---------------- Associative ----------------
std::map<std::string, int> ordered; // sorted, O(log n)
ordered["ada"] = 1815;
ordered["grace"] = 1906;
ordered["alan"] = 1912;
for (const auto& [name, year] : ordered) { // C++17 structured binding
std::cout << name << ' ' << year << '\n';
} // prints ada, alan, grace - sorted by key, not by insertion
std::unordered_map<std::string, int> fast; // hash table, average O(1)
fast["ada"] = 1815;
// Lookup: find returns an iterator, end() means not found.
if (auto it = ordered.find("grace"); it != ordered.end()) {
std::cout << "found " << it->second << '\n';
}
// operator[] INSERTS a default-constructed value when the key is
// missing, which surprises people. Use .at() or .find() to read,
// and .contains() (C++20) to test.
std::cout << ordered.contains("babbage") << '\n'; // 0, inserts nothing
std::set<int> unique_sorted{5, 1, 5, 3, 1}; // -> 1 3 5
// ---------------- Iterators ----------------
for (auto it = v.begin(); it != v.end(); ++it) {
std::cout << *it << ' '; // the range-based for does this for you
}
std::cout << '\n';
// end() is one PAST the last element. Never dereference it.
// ---------------- Algorithms ----------------
std::sort(v.begin(), v.end()); // ascending
std::sort(v.begin(), v.end(), std::greater<int>{}); // descending
std::reverse(v.begin(), v.end());
if (auto found = std::find(v.begin(), v.end(), 30); found != v.end()) {
std::cout << "index " << (found - v.begin()) << '\n';
}
int evens = std::count_if(v.begin(), v.end(),
[](int n) { return n % 2 == 0; });
int total = std::accumulate(v.begin(), v.end(), 0); // <numeric>
std::cout << evens << ' ' << total << '\n';
// Erase every element over 25. The erase-remove idiom: remove()
// shuffles the keepers forward and returns the new logical end;
// erase() then actually shortens the container.
v.erase(std::remove_if(v.begin(), v.end(),
[](int n) { return n > 25; }),
v.end());
// C++20 replaces all of that with: std::erase_if(v, pred);
return 0;
}
Discussion
No questions on this topic yet. Sign in to ask the first one.