The Standard Template Library (STL) in C++ is a collection of generic templates for containers (vector, map, set), iterators, algorithms (sort, find), and function objects. It lets you store and process data without writing low-level data-structure code. STL ships with every standard C++ compiler, works with any data type, and is used through headers such as ,
, and .
The standard template library in C++ gives you tested, ready-made data structures and algorithms, so you never have to write a linked list or a sorting routine from scratch. With one #include you get a dynamic array that manages its own memory, and with std::sort you get an optimized sorting algorithm that works on many data types.
Here is a pattern we see often in labs and firmware teams. A beginner builds a linked list from raw pointers, loses two days to a dangling pointer, and later discovers that std::list was available all along. Using STL well saves you from that kind of avoidable debugging.
This guide explains what STL in C++ is, why you should use it, its key concepts, its components, and the types of STL containers. Because IIES teaches embedded engineering, we also cover where STL fits on a microcontroller and where it does not.
Consider a task every embedded engineer meets: storing a variable number of sensor readings and finding the largest one. In plain C you manage a buffer, track its size, call realloc, check for failure, and write the search loop yourself. In C++ you write this:
std::vector readings;
readings.push_back(adcValue);
int peak = *std::max_element(readings.begin(), readings.end()); // readings must not be empty
The container handles memory, and the algorithm handles the search. These are the main reasons to use STL:
std::map lookups.std::sort works on integers, floats, structs, and strings, as long as the type can be compared.std::vector does.Engineer’s note: On an STM32 or ESP32 project, the real question is not “STL or no STL”. It is “which parts of STL, and with what memory policy”. std::array, std::string_view, and most functions never touch the heap. std::vector, std::map, and std::string do.
STL is built on C++ templates. When you write std::vector and std::vector, the compiler generates separate code for each type at compile time. You get type safety and no runtime dispatch cost, but every new type you instantiate adds code to your binary.
An iterator behaves like a pointer: you dereference it with * and move it with ++. Every container provides begin(), which points to the first element, and end(), which points one past the last element. The range [begin, end) is half-open, which is why you never dereference end().
STL defines iterator categories: input, output, forward, bidirectional, random access, and (since C++20) contiguous. The category decides which algorithms work with a container. For example, std::sort needs random access iterators, so it works on vector, deque, and array, but not on list. A list has its own list::sort() member function for that reason.
Algorithms such as std::find, std::sort, and std::accumulate work on iterator ranges, not on specific containers. This separation means a small set of algorithms serves every container.
The standard states how expensive operations are. vector::push_back is amortized O(1), map::find is O(log n), and unordered_map::find is O(1) on average. Choosing a container is mostly choosing which of these guarantees you need.
Containers own their elements and copy them by default. Since C++11, move semantics let containers transfer ownership cheaply, which is why returning a std::vector from a function is usually efficient.
Some operations make existing iterators invalid. If push_back forces a vector to reallocate, every iterator, pointer, and reference into that vector becomes invalid. This concept causes more STL bugs than any other, so learn it early.
The STL separates three jobs: containers store data, iterators walk through it, and algorithms process it. They connect like this:
Container --> begin() / end() iterators --> Algorithm --> Function object or lambda
(stores) (traverse) (processes) (customizes behavior)
When you call std::sort(v.begin(), v.end()), the algorithm never knows it is sorting a vector. It only sees two random access iterators. That is why you can pass a custom comparison, such as std::greater() or a lambda, and change the order without touching the algorithm.
Memory behavior matters in firmware. A std::vector keeps its elements in one contiguous heap block. When the block fills up, the vector allocates a larger one (the growth factor depends on the library, commonly 1.5x or 2x), moves the elements across, and frees the old block. Each reallocation is a moment of unpredictable latency and a source of heap fragmentation, which is why reserve() is a habit in embedded code.
The standard template library in C++ has four core components and two supporting ones.
| Component | Role | Main header | Example |
|---|---|---|---|
| Containers | Store collections of objects |
| std::vector |
| Iterators | Traverse containers and connect them to algorithms | v.begin() | |
| Algorithms | Search, sort, transform, and count | , | std::sort, std::accumulate |
| Function objects | Supply custom behavior to algorithms | std::greater, lambdas | |
| Container adaptors | Restricted interfaces over other containers | , | std::priority_queue |
| Allocators | Control how containers obtain memory | , | std::allocator, std::pmr |
Function objects are anything callable. In modern C++, lambdas are the usual choice:
auto highCount = std::count_if(v.begin(), v.end(), [](int x) { return x > 3000; });
Allocators deserve special attention in embedded work. A custom allocator, or a C++17 std::pmr memory resource, lets a container draw memory from a static buffer instead of the general heap. That gives you STL convenience with predictable memory use.
void*-based C code.for loops, lambdas, and move semantics arrived in C++11. Ranges and std::span arrived in C++20.STL containers fall into four groups: sequence containers, ordered associative containers, unordered associative containers, and container adaptors.
These store elements in a linear order that you control.
std::vector: a dynamic array in contiguous memory. This is the default choice.std::array: a fixed-size array wrapper. The size is known at compile time, the storage lives inside the object, and there is no heap use.std::deque: a double-ended queue with fast insertion and removal at both ends.std::list: a doubly linked list with O(1) insertion and erasure at a known position, but no random access.std::forward_list: a singly linked list with the lowest overhead of the linked containers.std::string is also a sequence container, holding characters.
std::set, std::multiset, std::map, and std::multimap keep their keys sorted. Implementations typically use a balanced binary search tree, commonly a red-black tree. Lookup, insertion, and removal cost O(log n). A set stores unique keys, a map stores key-value pairs, and the multi versions allow duplicate keys.
std::unordered_set, std::unordered_multiset, std::unordered_map, and std::unordered_multimap arrived in C++11. They use hash tables, so lookup is O(1) on average and O(n) in the worst case. They do not keep keys in any order.
std::stack (last in, first out), std::queue (first in, first out), and std::priority_queue (highest priority first) wrap another container and expose a limited interface. They have no iterators. By default, stack and queue use std::deque, and priority_queue uses std::vector.
vector, map, string, and similar types allocate dynamically. On a part with 64 KB of RAM, long-running firmware can fragment the heap and fail days after deployment, in a way you never saw on the bench. pulls in a large amount of library code, so firmware usually sends output through a UART driver or a lightweight printf instead.-fno-exceptions and -fno-rtti. With exceptions disabled, failures such as an out-of-range vector::at() end in abort() instead of a catchable exception, so you must design error handling deliberately.std::array, algorithms, and fixed-capacity containers.std::vector for waveform buffers and std::map for configuration tables.std::vector or std::array, and map register addresses to handlers with std::unordered_map.std::array and fixed-capacity containers.std::priority_queue for the open list.std::string, std::map, and std::function for MQTT topic handlers and device registries.std::array and for filters and avoids heap containers.std::vector..std::vector samples;push_back, or emplace_back. Call reserve() first if you know the size.for loop or with iterators.This program analyzes ADC samples and counts fault events. Compile it with g++ -std=c++17 -Wall -Wextra stl_demo.cpp -o stl_demo.
// stl_demo.cpp - Analyzing ADC samples and fault events with STL
#include // std::sort, std::count_if, std::minmax_element
#include // std::setprecision
#include // std::cout
#include
Expected output:
Min: 1987 Max: 4095
Average: 2431.1
Spikes above 3000: 2
Sorted: 1987 2033 2048 2060 2075 2101 3050 4095
OVERCURRENT -> 1
OVERTEMP -> 3
UNDERVOLTAGE -> 1
Firmware often cannot afford or heap containers. Here is the same idea written for a Cortex-M target, with no heap and a size known at compile time:
// Embedded-friendly median filter: no heap, fixed size
#include
#include
#include
static std::array<std::uint16_t, 8> adcWindow{}; // static storage (.bss), no heap
std::uint16_t medianOfWindow()
{
std::array<std::uint16_t, 8> copy = adcWindow; // 16-byte stack copy
std::sort(copy.begin(), copy.end());
return static_cast((copy[3] + copy[4]) / 2); // median of 8 samples
}
Typical implementations of std::sort work in place without allocating memory, but confirm this for your toolchain by checking the map file.
or is the most common beginner compile error.std::vector samples{...}: the initializer list fills the vector, and push_back grows it automatically.std::minmax_element: finds the smallest and largest elements in one pass and returns a pair of iterators. You dereference them with *.std::accumulate with 0.0: the initial value decides the result type. Starting from 0 (an int) would produce an integer sum and a truncated average.std::count_if: the lambda is the function object that defines what counts as a spike.std::sort: rearranges the vector in place, so earlier iterators no longer point at the same values.std::map: keeps keys sorted alphabetically, which is why the output lists OVERCURRENT first. The expression ++faultCount[e] creates a missing key with value 0 and then increments it.std::array stores its 8 elements inside the object, so there is no allocation, and the sort works on a stack copy.Common errors in this code:
std::minmax_element on an empty vector returns end() iterators, and dereferencing them is undefined behavior. Check samples.empty() first.faultCount[name] only to test whether a key exists adds the key. Use find() instead.std::endl in a hot loop flushes the stream every time. Prefer '\n' when you do not need a flush.Best practices shown: const auto& in the range-based for loop avoids copies, algorithms replace hand-written loops, and a heap-free variant exists for firmware.
| Container | Element access | Insert / erase | Memory layout | Uses heap? | Best for |
|---|---|---|---|---|---|
| std::array | O(1) | Not applicable (fixed size) | Contiguous, inside the object | No | Fixed-size buffers, lookup tables |
| std::vector | O(1) | End: amortized O(1); middle: O(n) | Contiguous | Yes | Default choice for sequences |
| std::deque | O(1) | Both ends: O(1); middle: O(n) | Chunks of contiguous blocks | Yes | Queues, sliding windows |
| std::list | O(n) | O(1) at a known position | Separate nodes | Yes, per node | Frequent middle edits, stable iterators |
| std::forward_list | O(n) | O(1) after a known position | Separate nodes | Yes, per node | Smallest linked-list overhead |
std::map / std::set | O(log n) | O(log n) | Tree nodes | Yes, per node | Sorted keys, range queries |
std::unordered_map / std::unordered_set | O(1) average | O(1) average | Hash buckets and nodes | Yes | Fast key lookup without ordering |
| std::priority_queue | Top: O(1) | Push and pop: O(log n) | Heap inside a vector | Yes, via the vector | Schedulers, top-k, shortest-path |
Fact: these complexities are guarantees from the C++ standard. Recommendation: start with std::vector and change only when a measurement tells you to. Contiguous memory is often faster than the textbook complexity suggests. On Cortex-M0, M3, and M4 parts, which have no data cache, the bigger cost of linked and tree containers is memory: each node typically carries pointers plus allocator overhead on top of your data.
std::vector. Switch only when your access pattern or a measurement justifies it.reserve() when you know roughly how many elements you will store. Fact: this avoids repeated reallocations and keeps iterators valid as long as you stay within the reserved capacity.std::count_if says more than a loop with a counter.const auto& in range-based for loops to avoid copying elements, and use emplace_back to construct elements in place.at() during development and testing because it checks bounds. Keep unchecked operator[] for code paths you have verified.std::array, a fixed-capacity container such as those in the Embedded Template Library (ETL), or a std::pmr pool backed by a static buffer.v.erase(std::remove(v.begin(), v.end(), x), v.end());, or with std::erase_if in C++20.Why it happens: Iterators look like pointers into stable memory.
Impact: Undefined behavior, often an intermittent crash that depends on when a reallocation happens.
How professionals avoid it: They treat push_back, insert, and erase as events that may invalidate iterators. They reacquire iterators after a change, use the iterator that erase returns, and call reserve() up front.
operator[] on std::map to look up a keyWhy it happens: It looks like reading an array element.
Impact: A missing key is silently inserted with a default value. The map grows, and later logic sees a key that was never set.
How professionals avoid it: They use find(), contains() (C++20), or at() for lookups, and operator[] only when insertion is the intent.
std::remove without eraseWhy it happens: The name suggests that elements are removed.
Impact: std::remove only shifts the elements you keep toward the front and returns a new logical end. The container size does not change, and the leftover tail holds unspecified values.
How professionals avoid it: They always pair it with erase, or they call std::erase_if in C++20.
std::vector like a normal vectorWhy it happens: It looks like every other std::vector.
Impact: It is a space-optimized specialization that packs bits and returns proxy objects. You cannot take the address of an element or pass it where a bool* is expected.
How professionals avoid it: They use std::vector, std::array<bool, N>, or std::bitset, depending on the need.
Why it happens: It is a desktop habit, and the code compiles without complaint.
Impact: Allocation time is unbounded, the heap fragments, and out-of-memory failures appear after days of uptime.
How professionals avoid it: They pre-allocate during initialization, use fixed-capacity containers, and keep ISRs free of allocation.
-Wall -Wextra, and build host-side unit tests with -fsanitize=address,undefined to catch out-of-bounds access and undefined behavior early._GLIBCXX_DEBUG on host builds to catch invalid iterator use and out-of-range access. Define it consistently in every translation unit. _GLIBCXX_ASSERTIONS is a lighter option that adds cheap checks such as bounds checks in operator[].at() while debugging. It reports an out-of-range index instead of silently reading garbage.print v shows the elements instead of raw internal pointers.error: line and from the “required from here” lines that point at your code. The long middle section is usually noise.arm-none-eabi-nm -C --size-sort -S firmware.elf and read the linker’s -Wl,--print-memory-usage summary.vector::reserve() and unordered_map::reserve() avoid repeated reallocation and rehashing.vector and array usually beat list and map on small and medium data because they need fewer allocations and less pointer overhead.std::sort, then search with std::lower_bound for O(log n) lookups and no per-node allocation.const&, return them by value (move semantics and copy elision handle the cost), and use emplace_back.std::string_view (C++17) and std::span (C++20) read existing data without allocating.std::pmr::monotonic_buffer_resource over a static buffer gives containers predictable memory. It releases memory only when the resource is released or destroyed, so it suits allocate-once designs. libstdc++ provides it from GCC 9. on microcontrollers: send output through a UART driver or a lightweight printf instead.std::span make STL code shorter and safer.std::expected offers error handling without exceptions, which suits embedded builds. std::flat_map and std::flat_set store sorted data contiguously, which brings the sorted-vector technique into the standard library. Check your compiler’s support before using them.std::inplace_vector, a vector with fixed capacity and no heap use, was added to the C++26 working draft. Confirm toolchain support before relying on it.The standard template library in C++ replaces hand-written data structures with tested components. Containers store data, iterators traverse it, algorithms process it, and function objects customize the behavior. Start with std::vector, learn the four container groups, and understand iterator invalidation before you write production code.
For embedded work, use STL deliberately. std::array, , and view types cost nothing in heap terms, while dynamic containers need a memory policy. Run the code example in this guide, then rebuild it with std::array for a Cortex-M target and compare the memory behavior.
The standard template library in C++ is a set of generic, reusable components, namely containers, iterators, algorithms, and function objects, that come with every standard C++ compiler. It lets you store data in structures like vector and map and process it with ready-made functions like sort and find, without writing the underlying data-structure code yourself.
Use STL to save development time, reduce bugs, and get efficient, well-tested implementations. Containers manage memory for you, algorithms have documented complexity, and the same code works across compilers and platforms. For embedded work, STL also makes firmware logic easier to read and unit-test on a PC before it runs on hardware.
STL has four core components: containers (vector, map, set), iterators (generalized pointers that traverse containers), algorithms (sort, find, accumulate), and function objects (functors and lambdas). Two supporting pieces are container adaptors such as stack and queue, and allocators, which control how containers obtain memory. Together they separate data storage from data processing.
STL containers fall into four groups. Sequence containers keep elements in a linear order that you control: vector, array, deque, list, and forward_list. Ordered associative containers (set, map, multiset, multimap) keep keys sorted. Unordered associative containers (unordered_set, unordered_map) use hashing for fast average lookup. Container adaptors (stack, queue, priority_queue) wrap another container with a restricted interface.
STL was the original generic library designed at HP in the 1990s and later adopted into the C++98 standard. Today its containers, iterators, algorithms, and function objects are part of the C++ Standard Library, which also includes streams, strings, threads, and more. In everyday conversation, developers use “STL” to mean those template-based parts of the standard library.
Yes, selectively. std::array, std::span, std::string_view, and most of the functions need no heap and work well on Cortex-M devices. Heap-based containers such as vector, map, and string can cause fragmentation and unpredictable timing, so many teams restrict or replace them with fixed-capacity alternatives like the Embedded Template Library (ETL). Always check your project’s coding standard and memory budget.
Indian Institute of Embedded Systems – IIES