Standard library
The C++ standard library covers a substantially wider surface than C’s, and grows significantly with each revision. The principal sub-libraries — strings, containers, algorithms, ranges, iostreams, memory management, utilities, time, filesystem, formatting, threading — are documented in their own pages where the topic warrants. This page provides a survey of the headers and a route to the in-depth treatment. The library is the single largest practical advantage of C++ over its less-batteries-included peers; nearly every non-trivial C++ program uses it heavily, and familiarity with it is a substantial part of fluency in the language.
The C++ library distinguishes the C++-native components from the C-inherited components. Each C standard header has a C++ counterpart with a c prefix and no extension: <stdio.h> becomes <cstdio>, <string.h> becomes <cstring>, and so on. The C++ versions place the declarations in namespace std (and may additionally place them in the global namespace, implementation-defined). Modern code uses <cstdio> rather than <stdio.h> for the qualification.
The shape of the library
The library is loosely structured into:
- The general utilities —
<utility>,<tuple>,<optional>,<variant>,<expected>,<any>. - Strings and views —
<string>,<string_view>,<format>,<print>(C++23). - Containers —
<array>,<vector>,<deque>,<list>,<forward_list>,<map>,<set>,<unordered_map>,<unordered_set>,<stack>,<queue>,<span>,<mdspan>. - Algorithms and ranges —
<algorithm>,<numeric>,<ranges>. - Memory —
<memory>,<memory_resource>,<new>. - Time —
<chrono>. - Filesystem —
<filesystem>. - I/O —
<iostream>,<fstream>,<sstream>,<iomanip>,<istream>,<ostream>,<streambuf>,<print>. - Concurrency —
<thread>,<jthread>,<mutex>,<shared_mutex>,<condition_variable>,<future>,<atomic>,<barrier>,<latch>,<semaphore>,<stop_token>. - Coroutines —
<coroutine>,<generator>(C++23). - Type system —
<type_traits>,<concepts>,<typeinfo>. - Numerics —
<cmath>,<numeric>,<random>,<complex>,<bit>,<numbers>. - Error handling —
<exception>,<stdexcept>,<system_error>,<expected>. - C compatibility —
<cstdio>,<cstdlib>,<cstring>,<cmath>,<ctime>,<cctype>,<cassert>, etc.
The library is large enough that working programmers are not expected to know every corner; the survey here covers the headers a working C++ programmer encounters routinely.
Strings
Treated in Strings. The principal headers:
<string>—std::string,std::wstring,std::u8string,std::u16string,std::u32string.<string_view>— non-owning views.<format>(C++20) —std::format,std::format_to, type-safe formatting.<print>(C++23) —std::print,std::printlnfor direct formatted output.<cstring>,<cctype>— C-inherited byte and character functions.
Containers
Treated in Data structures. The principal headers and types:
| Header | Types |
|---|---|
<array> | std::array<T, N> |
<vector> | std::vector<T> |
<deque> | std::deque<T> |
<list> | std::list<T> |
<forward_list> | std::forward_list<T> |
<map> | std::map<K, V>, std::multimap<K, V> |
<set> | std::set<K>, std::multiset<K> |
<unordered_map> | std::unordered_map<K, V>, std::unordered_multimap<K, V> |
<unordered_set> | std::unordered_set<K>, std::unordered_multiset<K> |
<stack> | std::stack<T> |
<queue> | std::queue<T>, std::priority_queue<T> |
<span> (C++20) | std::span<T> |
<mdspan> (C++23) | std::mdspan<T, Extents> |
Algorithms and ranges
Treated in Functional and ranges. The principal headers:
<algorithm>— the iterator-based algorithms (sort,find,transform,accumulate).<numeric>— numeric reductions and scans (accumulate,reduce,transform_reduce,partial_sum,inner_product,iota).<ranges>(C++20) — range-based algorithms and the views library.<execution>(C++17) — execution policies for parallel algorithms.
Memory
Treated in Memory and RAII. The principal types and headers:
<memory>—std::unique_ptr<T>,std::shared_ptr<T>,std::weak_ptr<T>,std::make_unique,std::make_shared,std::allocator<T>,std::addressof.<memory_resource>(C++17) — polymorphic allocators.<new>—std::nothrow,std::bad_alloc, placement-new operators.<bit>(C++20) —std::bit_cast, bit-manipulation operations.
Utility types
The utility headers carry a substantial set of small but heavily-used types:
<utility>
std::pair<T1, T2> — a heterogeneous two-element tuple. Used as the value type of std::map, as a return type for functions that produce two related values, and as a building block for higher-arity tuples.
std::pair<int, std::string> p{42, "hello"};
auto [n, s] = p; // structured binding
std::move, std::forward, std::swap — covered in Move semantics.
std::exchange(obj, new) — atomically replaces obj with new and returns the old value. Useful in move constructors and destructors:
Widget(Widget &&other) noexcept : ptr_(std::exchange(other.ptr_, nullptr)) {}
<tuple>
std::tuple<T1, T2, ..., Tn> — a heterogeneous fixed-arity collection:
#include <tuple>
std::tuple<int, std::string, double> t{42, "hello", 3.14};
auto [n, s, d] = t; // structured binding
auto first = std::get<0>(t); // index-based access
auto found = std::get<std::string>(t); // type-based access (C++14)
std::tuple is conventional for multi-value returns when the values are not closely related and a class would be overkill.
<optional>
std::optional<T> (C++17) — an optional T. Treated in Functional and ranges and Error handling.
<variant>
std::variant<Ts...> (C++17) — a tagged union. Treated in Pattern matching and Functional and ranges.
<expected>
std::expected<T, E> (C++23) — a value-or-error type. Treated in Error handling.
<any>
std::any (C++17) — a type-erased holder for any value:
#include <any>
std::any a = 42;
a = std::string{"hello"};
a = 3.14;
if (a.type() == typeid(double)) {
double d = std::any_cast<double>(a);
}
The construction is occasionally useful for heterogeneous storage where the alternatives (variant with a fixed type list, type erasure via inheritance) are inappropriate. It carries runtime overhead and should not be the default.
<chrono>
Treated briefly here; it is a substantial library in its own right.
The principal types:
std::chrono::system_clock— wall-clock time.std::chrono::steady_clock— monotonic time, suitable for timing.std::chrono::high_resolution_clock— the highest-resolution clock available.std::chrono::duration<Rep, Period>— a time duration with arbitrary representation and tick period.std::chrono::time_point<Clock, Duration>— a point in time on a particular clock.
The convenience aliases std::chrono::nanoseconds, std::chrono::milliseconds, std::chrono::seconds, std::chrono::hours, etc., cover the common cases.
#include <chrono>
using namespace std::chrono;
auto start = steady_clock::now();
do_work();
auto end = steady_clock::now();
auto elapsed_ms = duration_cast<milliseconds>(end - start).count();
std::cout << "elapsed: " << elapsed_ms << " ms\n";
User-defined literals (5s, 100ms, 1h) are conventional:
using namespace std::chrono_literals;
std::this_thread::sleep_for(500ms);
auto deadline = system_clock::now() + 30s;
C++20 added a substantial calendar library — year, month, day, weekday, month_day, year_month_day, time-zone support — and <format> integration for date formatting:
auto today = std::chrono::system_clock::now();
std::cout << std::format("{:%Y-%m-%d}\n", today);
<filesystem>
C++17’s filesystem library:
#include <filesystem>
namespace fs = std::filesystem;
fs::path p = "/etc/passwd";
if (fs::exists(p) && fs::is_regular_file(p)) {
auto sz = fs::file_size(p);
std::cout << p << " is " << sz << " bytes\n";
}
for (const auto &entry : fs::recursive_directory_iterator("/var/log")) {
if (entry.is_regular_file()) {
std::cout << entry.path() << '\n';
}
}
The library covers paths, directory iteration, file metadata, copy/move/remove, permissions, and symbolic links. It abstracts over Unix and Windows filesystem APIs; portable code uses it in preference to the platform-specific calls.
<format> and <print>
C++20’s std::format and C++23’s <print> are the modern formatting interface. Treated in Strings and I/O streams.
#include <format>
#include <print>
auto s = std::format("{} is {} years old\n", name, age);
std::print("{} is {} years old\n", name, age);
std::println("done.");
The format-string mini-language is the inheritor of Python’s str.format and Rust’s println!. The interface is type-safe (the format string is checked against the argument types when it is a constexpr) and faster than <iostream> formatting in most measurements.
Threading and concurrency
Treated in Concurrency. The principal headers:
<thread>—std::thread,std::this_thread.<jthread>— implicit in<thread>since C++20; providesstd::jthreadandstd::stop_token.<mutex>,<shared_mutex>— mutual exclusion.<condition_variable>— signalling and waiting.<future>—std::async,std::future,std::promise.<atomic>— atomic operations and the memory model.<barrier>,<latch>,<semaphore>(C++20) — coordination primitives.<stop_token>— cooperative cancellation.
Type traits and concepts
The type-system introspection library:
<type_traits>— compile-time type predicates and transformations:std::is_integral,std::remove_const,std::decay,std::common_type,std::is_invocable, dozens more.<concepts>(C++20) — standard concepts:std::same_as,std::convertible_to,std::integral,std::floating_point,std::copyable,std::movable,std::regular,std::predicate, dozens more.<typeinfo>— thestd::type_infoclass returned bytypeid.
The traits are the building blocks of generic code; the concepts are the constraint vocabulary.
Numerics
The numeric facilities:
<cmath>— math functions:sqrt,sin,cos,pow,log,exp, etc., infloat,double, andlong doubleprecision.<numeric>—accumulate,reduce,transform_reduce,gcd,lcm,iota,inner_product,partial_sum.<random>— random number generation: distributions (uniform_int_distribution,normal_distribution), engines (mt19937,random_device).<complex>— complex numbers.<bit>(C++20) —bit_cast,popcount,countl_zero,countr_zero,bit_floor,bit_ceil,rotr,rotl.<numbers>(C++20) — math constants:std::numbers::pi,std::numbers::e,std::numbers::sqrt2.
#include <random>
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 100);
int n = dist(rng);
The <random> library is substantial and was a significant improvement over the C rand() family; production C++ uses it for any random-number generation.
Error handling
<exception>—std::exception,std::current_exception,std::nested_exception,std::throw_with_nested.<stdexcept>— the exception class hierarchy (runtime_error,logic_error,out_of_range, etc.).<system_error>—std::error_code,std::error_category, the standard error categories.<cassert>—assert.<expected>(C++23) —std::expected.
C compatibility
Every C standard header has a C++ counterpart with a c prefix:
| C header | C++ header |
|---|---|
<stdio.h> | <cstdio> |
<stdlib.h> | <cstdlib> |
<string.h> | <cstring> |
<math.h> | <cmath> |
<time.h> | <ctime> |
<ctype.h> | <cctype> |
<errno.h> | <cerrno> |
<stdint.h> | <cstdint> |
<stddef.h> | <cstddef> |
<assert.h> | <cassert> |
The C++ versions place the declarations in namespace std. The conventional discipline:
- Use the C++ header when available; refer to the names as
std::strlen,std::printf,std::time_t. - Reserve the C-headers for code that explicitly straddles the C/C++ boundary.
Modules: import std;
C++23 admitted import std;, which imports the entire standard library as a single statement:
import std;
int main() {
std::println("Hello, {}!", "world");
std::vector<int> v{1, 2, 3, 4, 5};
auto sum = std::accumulate(v.begin(), v.end(), 0);
std::println("sum: {}", sum);
}
The compilation is substantially faster than the equivalent inclusion-model code: the standard library is parsed once and imported as a precompiled module. Compiler and toolchain support is maturing; expect import std; to gradually replace the per-header #include pattern in code targeting C++23 and beyond.
A note on Boost and other libraries
Beyond the standard library, the C++ ecosystem has several large general-purpose libraries:
- Boost — a collection of many libraries, several of which have been incorporated into the standard (smart pointers, function objects, type traits, random numbers, filesystem, regex). Boost remains the staging area for new C++ features and the source of facilities not yet (or never) standardised.
- fmt — the predecessor of
std::format. Still widely used in code targeting older standards. - Abseil — Google’s open-source utility library; substantial overlap with the standard library and with Boost.
- range-v3 — the predecessor of C++20’s
<ranges>.
For new code, the standard library should be the default; third-party libraries fill the gaps the standard does not yet cover.