C++ Boost Library Cheat Sheet
Covers popular Boost C++ modules including Filesystem, StringAlgo, Asio networking, Optional, and lexical_cast for extending the standard library.
Boost.Filesystem
Portable filesystem path and directory operations.
#include <boost/filesystem.hpp>namespace fs = boost::filesystem;fs::path p = "/tmp/data/file.txt";std::cout << p.filename() << "\n"; // file.txtstd::cout << p.extension() << "\n"; // .txtstd::cout << p.parent_path() << "\n"; // /tmp/dataif (!fs::exists(p.parent_path())) { fs::create_directories(p.parent_path());}for (auto& entry : fs::directory_iterator("/tmp/data")) { std::cout << entry.path() << "\n";}
Boost.StringAlgo
Common string manipulation helpers not in the standard library.
#include <boost/algorithm/string.hpp>std::string s = " Hello, World! ";boost::trim(s); // "Hello, World!"boost::to_lower(s); // "hello, world!"std::vector<std::string> parts;boost::split(parts, s, boost::is_any_of(",")); // split on commabool starts = boost::starts_with(s, "hello");std::string joined = boost::join(parts, "-");
Boost.Asio TCP Client
Synchronous TCP socket connection with Boost.Asio.
#include <boost/asio.hpp>using boost::asio::ip::tcp;boost::asio::io_context io;tcp::resolver resolver(io);auto endpoints = resolver.resolve("example.com", "80");tcp::socket socket(io);boost::asio::connect(socket, endpoints);std::string request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";boost::asio::write(socket, boost::asio::buffer(request));boost::asio::streambuf response;boost::asio::read_until(socket, response, "\r\n");
Boost.Optional & lexical_cast
Nullable value wrapper and safe string/number conversion.
#include <boost/optional.hpp>#include <boost/lexical_cast.hpp>boost::optional<int> parseInt(const std::string& s) { try { return boost::lexical_cast<int>(s); } catch (const boost::bad_lexical_cast&) { return boost::none; }}if (auto value = parseInt("42")) { std::cout << *value; // 42}
Popular Boost Libraries
Widely used modules in the Boost collection.
- Boost.Asio- Asynchronous and synchronous networking and low-level I/O.
- Boost.Filesystem- Portable path manipulation and directory/file operations (mostly superseded by std::filesystem in C++17).
- Boost.Thread- Threading primitives predating and extending std::thread.
- Boost.Regex- Regular expressions (predates and extends std::regex).
- Boost.Beast- HTTP and WebSocket support built on top of Boost.Asio.
- Boost.Serialization- Serialize/deserialize C++ objects to/from various formats.
- Boost.Program_options- Command-line and config-file argument parsing.
Boost.Signals2
Thread-safe observer pattern via signal/slot connections.
#include <boost/signals2.hpp>boost::signals2::signal<void(int)> onScoreChanged;boost::signals2::connection conn = onScoreChanged.connect( [](int score) { std::cout << "Score: " << score << "\n"; });// slots run in connection order; combiners can aggregate return valuesonScoreChanged(42); // invokes all connected slotsconn.disconnect(); // or use a scoped_connection to auto-disconnect on scope exitboost::signals2::scoped_connection scoped( onScoreChanged.connect([](int s) { /* ... */ }));
Boost.MultiIndex
A single container queryable by several independent keys/orderings at once.
#include <boost/multi_index_container.hpp>#include <boost/multi_index/ordered_index.hpp>#include <boost/multi_index/member.hpp>struct Employee { int id; std::string name; int age; };using namespace boost::multi_index;typedef multi_index_container< Employee, indexed_by< ordered_unique<member<Employee, int, &Employee::id>>, ordered_non_unique<member<Employee, std::string, &Employee::name>> >> EmployeeTable;EmployeeTable table;table.insert({1, "Ada", 32});table.insert({2, "Grace", 45});auto& byName = table.get<1>();auto it = byName.find("Ada"); // lookup by the second index
Boost.Interprocess Shared Memory
Share data between unrelated OS processes via a named memory-mapped segment.
#include <boost/interprocess/shared_memory_object.hpp>#include <boost/interprocess/mapped_region.hpp>using namespace boost::interprocess;// writer processshared_memory_object shm(create_only, "MySharedMemory", read_write);shm.truncate(1024);mapped_region region(shm, read_write);std::memset(region.get_address(), 0, region.get_size());int* value = static_cast<int*>(region.get_address());*value = 42;// reader processshared_memory_object shm2(open_only, "MySharedMemory", read_only);mapped_region region2(shm2, read_only);int v = *static_cast<int*>(region2.get_address());shared_memory_object::remove("MySharedMemory"); // cleanup when done
Boost.Container flat_map
A sorted-vector-backed map/set with better cache locality than std::map for read-heavy workloads.
#include <boost/container/flat_map.hpp>boost::container::flat_map<std::string, int> scores;scores["alice"] = 90;scores["bob"] = 85;// stored contiguously and kept sorted by key; O(log n) lookup, O(n) insertauto it = scores.find("alice");if (it != scores.end()) std::cout << it->second;// reserve to amortize the O(n) insertion cost when bulk-loadingscores.reserve(1000);
More Boost Modules Worth Knowing
Additional widely-used libraries beyond the core set.
- Boost.Signals2- Thread-safe signal/slot observer pattern for decoupled event notification.
- Boost.MultiIndex- One container with multiple simultaneous indices (ordered, hashed, sequenced) over the same data.
- Boost.Interprocess- Shared memory, memory-mapped files, and interprocess synchronization primitives.
- Boost.Container- Drop-in alternative containers like flat_map/flat_set/small_vector with different performance tradeoffs than std containers.
- Boost.Spirit- Header-only parser generator using EBNF-like grammars expressed directly in C++ template code.
- Boost.Graph (BGL)- Generic graph data structures and algorithms (BFS, DFS, Dijkstra, topological sort).
- Boost.Intrusive- Intrusive containers where the node hooks live inside the object itself, avoiding separate allocations.
- Boost.Test- Unit testing framework predating widespread adoption of GoogleTest/Catch2, still common in older codebases.
Before pulling in a Boost module, check if the standard library now covers it - std::filesystem, std::optional, std::variant, and std::regex were all standardized versions of originally Boost-only features, reducing your dependency footprint.