C++ Standard Library: A Complete Overview
The C++ Standard Library (often called STL — Standard Template Library) is a powerful set of template classes and functions included with any C++ compiler. It provides ready-made, tested, and optimized solutions for the most common programming tasks: from working with dynamic arrays and strings to complex sorting and searching algorithms. Using the standard library significantly speeds up development, increases code reliability, and simplifies its maintenance.
In this article, we will thoroughly examine the main components of the C++ Standard Library: containers, algorithms, iterators, strings, input/output streams, and smart pointers. Each section will be accompanied by practical code examples.
Containers
Containers are classes designed for storing and organizing collections of data. They are divided into three main categories:
- Sequence containers: store elements in a linear order. Main representatives:
std::vector(dynamic array),std::list(doubly linked list),std::deque(double-ended queue). - Associative containers: store elements in a sorted manner, providing fast search. Examples:
std::set(set),std::map(key-value dictionary). - Unordered associative containers (C++11): use hash tables for even faster access. Examples:
std::unordered_set,std::unordered_map.
Example of working with std::vector and std::map:
#include <iostream>#include <vector>#include <map>#include <string>
int main() { // Sequence container std::vector<int> numbers = {10, 20, 30, 40}; numbers.push_back(50); // Adding to the end
std::cout << "Vector: "; for (int n : numbers) { std::cout << n << " "; } std::cout << std::endl;
// Associative container std::map<std::string, int> ages; ages["Alice"] = 30; ages["Bob"] = 25;
std::cout << "Alice's age: " << ages["Alice"] << std::endl; return 0;}Iterators
Iterators are a generalized way to access elements of a container. They work like "smart pointers" and allow uniform traversal of any containers. The main types of iterators are: begin() (pointer to the first element) and end() (pointer to the element past the last one).
Example of using an iterator to traverse std::list:
#include <iostream>#include <list>
int main() { std::list<double> prices = {19.99, 29.99, 9.99};
// Using an iterator for (auto it = prices.begin(); it != prices.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0;}Algorithms
The <algorithm> library contains dozens of ready-made functions for working with sequences of data: sorting, searching, copying, transforming, and much more. Algorithms work with iterators, which makes them universal.
Popular algorithms:
std::sort— sorting a range.std::find— finding the first occurrence of a value.std::copy— copying elements.std::accumulate— summing elements (from<numeric>).
Example of sorting and searching:
#include <iostream>#include <vector>#include <algorithm>
int main() { std::vector<int> data = {5, 2, 8, 1, 9