← C++ from Scratch Lesson 51 of 62 · 5 XP

Data structures and the STL

Theory

Machine translation, not yet reviewed by a native speaker.

A data structure is a way of storing many values so that the operations you need are fast. The STL (Standard Template Library) gives you ready-made ones:

container what it is fast slow
vector a dynamic array access by index, adding to the end inserting in the middle
list a doubly linked list inserting/removing anywhere (by iterator) access by index
deque a double-ended queue adding/removing at both ends inserting in the middle
stack a pile (LIFO) putting on / taking off the top —
queue a queue (FIFO) to the back / from the front —
set a sorted set without repeats searching, inserting (log n) —
map a key → value dictionary, in key order searching by key (log n) —
unordered_map / unordered_set a hash table searching in O(1) on average the order isn't kept

Complexity is written with O: O(1) — doesn't depend on the size, O(log n) — grows slowly (a million → ~20 steps), O(n) — proportional to the size, O(n²) — twice as much data = four times as long.

The three parts of the STL:

  1. containers — they store;
  2. iterators — "pointers" into a container, a single way of going through it;
  3. algorithms (<algorithm>) — sort, find, count_if… work with any container through iterators.

The default rule: if you don't know what to take, take std::vector.

Sign up for free to mark finished lessons and track your progress.