Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Libraries: core

What each language ships for everyday programming: printing, text, collections, iteration, optional values, errors and assertions, standard interfaces, numbers and bits, time and memory. Each entry compares the same role across languages.

Printing & formatting: console, fmt, println!, <print>

C++

C++ has two printing styles. <print> (C++23) and <format> (C++20) use {} placeholders checked at compile time: std::println prints and std::format returns a std::string. The older <iostream> streams (std::cout, std::cerr and <<) are still in most existing code. Both are part of the standard library.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <format>
#include <iostream>
#include <print>
#include <string>

int main() {
    std::string name = "Ada";
    int items = 3;

    std::println("{} has {} items", name, items); // C++23 <print>
    std::string label = std::format("{:>6}|{:03}", name, items); // C++20 <format>
    std::println("{}", label);
    std::println(stderr, "warning: low stock"); // standard error
    std::cout << name << " has " << items << " items\n"; // classic <iostream>
}

Most used: std::println, std::print, std::format, std::cout << ..., std::cerr. Format specs follow Python's: {:>6}, {:03}, {:.2f}, {:x}.

Text: String methods, strings, str/String, <string>

C++

std::string (<string>) is an owned, mutable sequence of bytes with find, substr, replace, append and +=, starts_with and ends_with (C++20) and contains (C++23). std::string_view (<string_view>) is a cheap, non-owning view for passing text without copying; it must not outlive the string it views. There is no built-in split or trim; write a small helper or use std::views::split.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cctype>
#include <print>
#include <string>
#include <string_view>

int main() {
    std::string raw = "  Ada Lovelace,Grace Hopper ";

    std::size_t comma = raw.find(',');
    std::string first = raw.substr(2, comma - 2); // "Ada Lovelace"
    std::string_view rest = std::string_view(raw).substr(comma + 1);

    std::println("{} {}", first, raw.contains("Grace")); // contains: C++23
    std::println("{} {}", first.starts_with("Ada"), rest);

    std::ranges::transform(first, first.begin(), [](unsigned char c) {
        return static_cast<char>(std::toupper(c));
    });
    first += "!";
    std::println("{}", first);
}

Most used: std::string, find, substr, +=, starts_with, contains, std::string_view, std::to_string, std::getline. Case conversion is per byte through <cctype>.

Text ↔ number conversion: Number, strconv, parse, <charconv>

C++

<charconv> provides std::from_chars and std::to_chars: fast, locale-independent conversions that report errors in a result struct instead of throwing. Check both the error code and how far parsing got, because "12px" parses 12 and stops. <string> has the older std::stoi and std::stod, which throw, and std::to_string.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <charconv>
#include <format>
#include <print>
#include <string>
#include <string_view>
#include <system_error>

int main() {
    for (std::string_view text : {"42", "3.5", "12px", ""}) {
        int value = 0;
        const char* end = text.data() + text.size();
        auto [stop, error] = std::from_chars(text.data(), end, value);
        bool whole = error == std::errc{} && stop == end;
        std::println("\"{}\" -> {} (whole string: {})", text, value, whole);
    }

    double d = std::stod("3.5"); // throws std::invalid_argument on bad input
    std::println("{} {} {}", d, std::to_string(42), std::format("{:.2f}", 3.14159));
}

Most used: std::from_chars, std::to_chars, std::stoi, std::stod, std::to_string, std::format("{:.2f}", x).

Collections: Array/Map/Set, slices/maps, std::collections, containers

C++

The containers library: std::vector (the default growable array), std::unordered_map and std::unordered_set (hash tables), std::map and std::set (sorted trees), std::deque, std::array (fixed size) and std::priority_queue. Each lives in its own header. map[key] inserts a default value when the key is missing, so use find or contains (C++20) just to check.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <deque>
#include <map>
#include <print>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

int main() {
    std::vector<int> scores{72, 95, 88}; // growable array
    scores.push_back(61);

    std::unordered_map<std::string, int> by_name{{"ada", 95}};
    by_name["grace"] = 88; // [] inserts when the key is missing
    bool has_linus = by_name.contains("linus"); // C++20

    std::unordered_set<std::string> tags{"go", "rust", "go"};
    std::map<std::string, int> sorted(by_name.begin(), by_name.end()); // ordered by key
    std::deque<int> queue{1, 2};
    queue.push_front(0);

    std::println("{} {} {}", scores.size(), std::ranges::max(scores), has_linus);
    std::println("{} {} {}", tags.size(), sorted.begin()->first, queue.front());
}

Most used: std::vector push_back/size, std::unordered_map, operator[], find, contains, insert_or_assign, std::map for ordered keys, std::array.

Collection algorithms: Array methods, slices, Iterator, <algorithm>

C++

<algorithm> has the classic algorithms (sort, find, count_if, transform, max_element, binary_search). C++20 <ranges> adds versions that take a whole container, such as std::ranges::sort(v), plus projections like &Order::total. Views (std::views::filter, transform, take) build lazy pipelines with |. <numeric> has accumulate and reduce for sums.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <functional>
#include <numeric>
#include <print>
#include <ranges>
#include <vector>

struct Order {
    int id;
    int total;
    bool paid;
};

int main() {
    std::vector<Order> orders{{1, 40, true}, {2, 15, false}, {3, 90, true}};

    auto paid_totals = orders
        | std::views::filter([](const Order& o) { return o.paid; })
        | std::views::transform(&Order::total);
    int revenue = std::accumulate(paid_totals.begin(), paid_totals.end(), 0);

    int unpaid = std::ranges::find(orders, false, &Order::paid)->id;
    std::ranges::sort(orders, std::greater{}, &Order::total); // descending

    std::println("{} {} {}", revenue, unpaid, orders[0].id);
}

Most used: std::ranges::sort, std::ranges::find, std::ranges::max, std::views::filter and transform, std::accumulate, std::count_if.

Iterators & generators: function*, iter.Seq, Iterator, <ranges>

C++

C++ iteration is built on iterators: any type with begin() and end() works in a range-for loop and with <algorithm>. C++20 <ranges> adds lazy views that generate or transform values on demand (iota for counting, possibly forever, plus transform, filter and take), and C++23 adds std::ranges::to for collecting into a container, plus zip, enumerate and stride (not yet in every standard library). C++23 also defines std::generator for co_yield coroutines, but some standard libraries, including libc++, do not ship it yet.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstddef>
#include <print>
#include <ranges>
#include <vector>

int main() {
    // Lazy views produce values on demand; nothing is stored.
    auto multiples = std::views::iota(0, 4) // 0, 1, 2, 3
        | std::views::transform([](int n) { return n * 3; });
    auto squares = std::views::iota(1) // counts forever
        | std::views::transform([](int n) { return n * n; })
        | std::views::take(4);

    for (int n : multiples) std::print("{} ", n);
    std::println("");

    auto collected = std::ranges::to<std::vector>(squares); // C++23
    for (std::size_t i = 0; int value : collected) // range-for with an initializer
        std::println("{} {}", i++, value);
}

Most used: range-for, begin() and end(), std::views::iota, transform, filter, take, enumerate, zip, std::ranges::to, custom iterator classes.

Optional & variant values: unions, comma-ok, Option, <optional>/<variant>

C++

<optional> provides std::optional<T> (a value or std::nullopt) and <variant> provides std::variant<A, B, ...> (exactly one of several types), which std::visit dispatches on. <any> holds a value of any copyable type. C++23 adds and_then, transform and or_else to optional. Reading the wrong alternative with std::get throws std::bad_variant_access, and *opt on an empty optional is undefined behaviour.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <map>
#include <optional>
#include <print>
#include <string>
#include <variant>

struct Pickup {};
struct Courier {
    std::string address;
};
using Shipping = std::variant<Pickup, Courier>; // exactly one of these

template <class... Fs>
struct overloaded : Fs... {
    using Fs::operator()...;
};

std::string describe(const Shipping& shipping, std::optional<std::string> note = {}) {
    std::string extra = note.value_or("no note");
    return std::visit(
        overloaded{
            [&](const Pickup&) { return "pickup (" + extra + ")"; },
            [&](const Courier& c) { return "courier to " + c.address + " (" + extra + ")"; },
        },
        shipping);
}

std::optional<std::string> find_name(const std::map<int, std::string>& names, int id) {
    auto it = names.find(id);
    if (it == names.end()) return std::nullopt;
    return it->second;
}

int main() {
    std::map<int, std::string> names{{7, "Ada"}};
    std::println("{}", find_name(names, 8).has_value());
    std::println("{}", describe(Courier{"1 Main St"}));
    std::println("{}", describe(Pickup{}, "fragile"));
}

Most used: std::optional, std::nullopt, value_or, has_value, std::variant, std::visit with an overloaded set of lambdas, std::holds_alternative, std::get_if.

Errors: Error, errors, Result + std::error, <stdexcept>/<expected>

C++

C++ has two error styles. Exceptions use throw, try and catch with the standard hierarchy in <stdexcept> (std::runtime_error, std::invalid_argument, std::out_of_range), all deriving from std::exception, whose what() returns the message. C++23 <expected> adds std::expected<T, E>, a return value that holds either a result or an error, much like Rust's Result. <system_error> covers operating-system error codes.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <expected>
#include <print>
#include <stdexcept>
#include <string>

std::expected<int, std::string> load(const std::string& id) { // C++23
    if (id != "1") return std::unexpected("order " + id + " not found");
    return 40;
}

int checked_quantity(int value) {
    if (value < 0) throw std::invalid_argument("quantity must be >= 0");
    return value;
}

int main() {
    if (auto total = load("7"); !total) std::println("missing: {}", total.error());

    try {
        checked_quantity(-1);
    } catch (const std::invalid_argument& error) {
        std::println("rejected: {}", error.what());
    }
}

Most used: throw std::runtime_error, catch (const std::exception& e), e.what(), std::expected, std::unexpected, std::error_code.

Assertions & invariants: node:assert, panic, assert!, <cassert>/static_assert

C++

assert(expr) from <cassert> prints the failed expression with file and line and calls std::abort; defining NDEBUG (as release builds usually do) removes it entirely, so never put side effects inside one. static_assert checks a constant expression at compile time. C++23 adds std::unreachable() in <utility> and the [[assume(expr)]] attribute: both are promises to the optimizer, not checks, and the behaviour is undefined if the promise is false. Contracts (pre, post, contract_assert) are C++26 and not available in C++23.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <cstdint>
#include <print>
#include <utility>

static_assert(sizeof(std::uint64_t) == 8, "need 64-bit integers"); // compile time

enum class Status { open, paid, shipped };

const char* label(Status s) {
    switch (s) {
        case Status::open: return "open";
        case Status::paid: return "paid";
        case Status::shipped: return "shipped";
    }
    std::unreachable(); // C++23: a promise every case returned; UB if reached
}

int split(int total, int parts) {
    assert(parts > 0 && "parts must be positive"); // removed when NDEBUG is defined
    [[assume(total >= 0)]]; // C++23 optimizer hint: never checked, UB if false
    return total / parts;
}

int main() {
    std::println("{} {}", label(Status::paid), split(10, 2));
#ifdef NDEBUG
    std::println("NDEBUG is set: assert is compiled out");
#else
    std::println("assert is active: a false one prints the expression and aborts");
#endif
}

Most used: assert(cond && "message"), static_assert(cond, "message"), std::unreachable() after an exhaustive switch, [[assume(x > 0)]], exceptions or std::expected for expected failures.

CMake Release and RelWithDebInfo builds pass -DNDEBUG, so assert does nothing there; use a check that throws or aborts when an invariant must hold in production.

Reaching std::unreachable() or a false [[assume]] is undefined behaviour: the optimizer may delete code around it. Use assert in debug builds to catch the mistake first.

Standard interfaces & traits: protocols, Stringer, derive, concepts

C++

C++ connects types to the library through operators, specializations and concepts rather than one interface mechanism. Defaulting operator<=> (C++20, <compare>) gives all comparisons in one line, specializing std::hash makes a type usable in unordered containers, and specializing std::formatter makes it printable with std::format. Concepts from <concepts> (std::totally_ordered, std::integral, std::invocable) constrain templates; virtual functions remain the tool for runtime polymorphism.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <compare>
#include <concepts>
#include <format>
#include <print>
#include <string>
#include <unordered_set>
#include <vector>

struct Money {
    long cents = 0;
    auto operator<=>(const Money&) const = default; // ==, <, >, ... in one line
};

template <>
struct std::hash<Money> { // lets Money be an unordered_set key
    std::size_t operator()(const Money& m) const noexcept { return std::hash<long>{}(m.cents); }
};

template <>
struct std::formatter<Money> : std::formatter<std::string> { // lets std::format print it
    auto format(const Money& m, std::format_context& ctx) const {
        auto text = std::format("${}.{:02}", m.cents / 100, m.cents % 100);
        return std::formatter<std::string>::format(text, ctx);
    }
};

template <std::totally_ordered T> // a C++20 concept constrains the template
T largest(const std::vector<T>& values) {
    return std::ranges::max(values);
}

int main() {
    std::vector<Money> prices{{500}, {1250}, {120}};
    std::ranges::sort(prices);
    std::unordered_set<Money> unique(prices.begin(), prices.end());
    std::println("{} {} {}", prices[0], largest(prices), unique.size());
}

Most used: operator<=> = default, operator==, std::hash and std::formatter specializations, operator<< for streams, std::integral and std::same_as, virtual and override.

Functions as values: closures, func types, Fn traits, <functional>

C++

<functional> holds the tools for passing behaviour around: std::function stores any callable with a given signature (a lambda, a function pointer or an object with operator()), std::bind_front fixes leading arguments, std::invoke calls anything callable and std::ref passes references through. Templates that take an auto or F parameter avoid std::function's overhead. <utility> adds std::move, std::swap, std::exchange and std::pair, and <tuple> holds fixed groups of values.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <functional>
#include <map>
#include <print>
#include <string>
#include <utility>
#include <vector>

using Handler = std::function<int(int)>; // holds any callable with this signature

Handler compose(std::vector<Handler> steps) {
    return [steps = std::move(steps)](int n) {
        for (const auto& step : steps) n = step(n);
        return n;
    };
}

int add(int a, int b) { return a + b; }

int main() {
    std::map<std::string, Handler> handlers{
        {"double", [](int n) { return n * 2; }},
        {"tax", [](int n) { return n * 12 / 10; }},
    };
    Handler add_fee = std::bind_front(add, 5); // fixes the first argument
    auto pipeline = compose({handlers["double"], handlers["tax"], add_fee});
    std::println("{}", pipeline(10));

    auto [a, b] = std::pair{1, 2}; // structured bindings
    std::swap(a, b);
    int old = std::exchange(a, 10); // set a new value, get the old one back
    std::println("{} {} {} {}", a, b, old, std::invoke(add, 2, 3));
}

Most used: lambdas with [&], [=] or [x = std::move(y)], std::function, std::bind_front, std::invoke, std::move, std::swap, std::exchange, std::pair, std::tuple, structured bindings.

Math & random numbers: Math, math + math/rand, number methods, <cmath>/<random>

C++

<cmath> has the math functions (sqrt, pow, round, floor, abs, sin, log, hypot) and <limits> reports type ranges through std::numeric_limits. <random> separates engines (std::mt19937) from distributions (uniform_int_distribution, normal_distribution): seed an engine once, then draw from a distribution. rand() from <cstdlib> is legacy, and std::random_device is the usual seed source (the standard allows it to be deterministic), and distribution output differs between standard libraries, so do not rely on exact sequences across platforms.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cmath>
#include <limits>
#include <print>
#include <random>

int main() {
    std::println("{} {} {}", std::round(2.5), std::floor(-1.5), std::trunc(-1.5));
    std::println("{} {} {}", std::max(9, 4), std::abs(-7), std::sqrt(16.0));
    std::println("{}", std::numeric_limits<long long>::max());

    std::mt19937 engine{std::random_device{}()}; // seed a generator once
    std::uniform_int_distribution<int> die{1, 6}; // inclusive range
    std::println("{}", die(engine));
}

Most used: std::sqrt, std::pow, std::round, std::abs, std::numeric_limits<T>::max, std::mt19937, std::uniform_int_distribution, std::random_device.

Integer & bit math: bitwise ops + Math.clz32, math/bits, integer methods, <bit>/<numeric>

C++

<bit> (C++20) has popcount, countl_zero and countr_zero, rotl and rotr, bit_width, has_single_bit (is a power of two), bit_ceil and bit_floor, plus std::byteswap in C++23; they accept only unsigned integer types. <numeric> has std::gcd, std::lcm and std::midpoint (C++17), which computes the middle of two values without overflow. Unsigned arithmetic wraps modulo 2^N, but signed overflow is undefined behaviour, so check against std::numeric_limits before the operation. Saturating functions such as std::add_sat arrive in C++26.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <bit>
#include <cstdint>
#include <limits>
#include <numeric>
#include <print>

bool add_would_overflow(int a, int b) { // check before adding: signed overflow is UB
    return (b > 0 && a > std::numeric_limits<int>::max() - b) ||
           (b < 0 && a < std::numeric_limits<int>::min() - b);
}

int main() {
    std::uint32_t x = 0b1011'0110;
    std::println("{} {} {} {}", std::popcount(x), std::countl_zero(x), std::countr_zero(x),
                 std::bit_width(x));
    std::println("{:08b} {:#x}", std::rotl(std::uint8_t{0b1000'0001}, 1),
                 std::byteswap(std::uint16_t{0x1234})); // byteswap is C++23
    std::println("{} {} {}", std::has_single_bit(64u), std::bit_ceil(100u), std::bit_floor(100u));

    int a = 2'000'000'000, b = 2'100'000'000;
    std::println("{} {} {}", std::gcd(84, 36), std::lcm(4, 6), std::midpoint(a, b)); // no a + b

    unsigned u = std::numeric_limits<unsigned>::max();
    u += 1; // unsigned arithmetic wraps: defined behaviour
    std::println("{} {}", u, add_would_overflow(std::numeric_limits<int>::max(), 1));
}

Most used: std::popcount, std::countl_zero, std::countr_zero, std::bit_width, std::has_single_bit, std::bit_ceil, std::rotl, std::gcd, std::midpoint, std::numeric_limits<T>::max.

std::popcount(42) does not compile because 42 is an int; write 42u or cast to an unsigned type.

Shifting by a negative count or by the type width or more is undefined; -fsanitize=undefined reports it, and signed overflow, at run time.

Big numbers & decimals: BigInt, math/big, num-bigint, Boost.Multiprecision

C++

The standard library has only fixed-size integers (up to 64 bits, plus the __int128 extension in GCC and Clang, not MSVC) and binary floats. Unsigned overflow wraps around; signed overflow is undefined behaviour. Boost.Multiprecision adds arbitrary-precision integers (cpp_int) and decimal floating point (cpp_dec_float), and GMP (through gmpxx) is the fastest option for heavy number theory.

Complete program

Complete program.

Before you use this

Not in the standard library: Boost 1.80+ (Boost.Multiprecision is header-only) from vcpkg, Conan or your system package manager.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <cstdint>
#include <iostream>
#include <limits>

namespace mp = boost::multiprecision;

int main() {
    mp::cpp_int big = mp::pow(mp::cpp_int(2), 100); // arbitrary-precision integer
    std::cout << big << '\n';

    std::uint64_t max = std::numeric_limits<std::uint64_t>::max();
    std::uint64_t wrapped = max + 1; // unsigned overflow wraps to 0
    std::cout << wrapped << '\n';

    mp::cpp_dec_float_50 price("19.99"); // 50 decimal digits
    std::cout << price * 3 << ' ' << (0.1 + 0.2 == 0.3) << '\n';
}

Most used: std::int64_t, std::numeric_limits, __int128, boost::multiprecision::cpp_int, cpp_dec_float_50, GMP's mpz_class.

Time & durations: Date + performance, time, std::time, <chrono>

C++

<chrono> models time with typed durations (milliseconds, seconds, days), clocks (steady_clock for measuring, system_clock for wall time) and time points. Literals such as 50ms come from std::chrono_literals. C++20 added calendar types (year_month_day), time zones (zoned_time; not yet in every standard library, check yours) and formatting through std::format. Lossy unit conversions need duration_cast.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <chrono>
#include <print>
#include <thread>

int main() {
    using namespace std::chrono;
    auto start = steady_clock::now(); // monotonic, for measuring

    auto now = system_clock::now(); // wall clock (UTC)
    std::println("{:%Y-%m-%d %H:%M}", floor<minutes>(now));
    std::println("{}", duration_cast<seconds>(now.time_since_epoch()).count());

    std::this_thread::sleep_for(50ms);
    auto tomorrow = floor<days>(now) + days{1};
    std::println("{:%F}", tomorrow);

    std::println("took {}", duration_cast<milliseconds>(steady_clock::now() - start));
}

Most used: steady_clock::now, system_clock::now, duration_cast, std::this_thread::sleep_for, 50ms literals, floor<days>, std::format("{:%F}", t).

Unicode & localization: Intl, unicode/utf8, char methods, <locale>/ICU

C++

The C++ standard library has almost no Unicode support: std::string holds bytes, std::u8string and char8_t mark UTF-8 in the type, and <locale> with the L format flag gives basic locale-aware formatting. The old <codecvt> converters are deprecated. Real Unicode work (code points, grapheme breaks, normalization, collation and case mapping) uses ICU, or smaller libraries such as utfcpp and simdutf.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstddef>
#include <print>
#include <string>
#include <string_view>

// Count code points by skipping UTF-8 continuation bytes (10xxxxxx).
std::size_t count_code_points(std::string_view utf8) {
    std::size_t count = 0;
    for (unsigned char byte : utf8)
        if ((byte & 0xC0) != 0x80) ++count;
    return count;
}

int main() {
    std::string word = "café👍🏽"; // std::string holds the UTF-8 bytes
    std::u8string marked = u8"café"; // char8_t marks UTF-8 in the type

    std::println("{} {}", word.size(), count_code_points(word)); // 13 bytes, 6 code points
    std::println("{}", marked.size());
    std::println("{:L}", 1234567); // uses the global locale ("C" unless you set one)
}

Most used: std::string as UTF-8 bytes, char8_t and std::u8string, std::locale, std::format("{:L}", n), ICU's icu::UnicodeString, BreakIterator and Collator.

Memory & smart pointers: GC, Box/Rc/Arc, <memory>

C++

<memory> provides the smart pointers that replace manual new and delete: std::unique_ptr (a single owner, freed when it goes out of scope, movable but not copyable), std::shared_ptr (reference-counted shared ownership) and std::weak_ptr (observes a shared_ptr without keeping it alive). Create them with make_unique and make_shared. Containers such as std::vector already manage their own memory.

Complete program

Complete program. Standard library: ships with your compiler, no install.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <memory>
#include <print>
#include <string>
#include <utility>

struct Config {
    std::string name;
};

int main() {
    auto owned = std::make_unique<Config>("dev"); // single owner; C++20 aggregate ( ) init
    auto moved = std::move(owned); // ownership transfers; owned is now null

    auto shared = std::make_shared<Config>("prod"); // reference counted
    std::shared_ptr<Config> other = shared;
    std::weak_ptr<Config> observer = shared; // does not keep it alive

    std::println("{} {}", owned == nullptr, moved->name);
    std::println("{} {}", shared.use_count(), observer.expired());
}

Most used: std::make_unique, std::unique_ptr, std::move, std::make_shared, std::shared_ptr, std::weak_ptr::lock, use_count.