Lesson 19-C++ Standard Library

The C++ Standard Library (STL, Standard Template Library) is a core component of the C++ language, providing efficient and generic data structures and algorithms that cover nearly all programming scenarios, from input/output to memory management and concurrent programming. This article provides a comprehensive analysis from core components to C++20 new features, helping developers master the design philosophy and practical applications of the standard library.

Standard I/O Streams

Standard I/O streams are the core tools in C++ for handling input and output, encapsulating input/output operations in an object-oriented manner, supporting formatted input, error handling, and cross-platform compatibility.

Core Header Files and Objects

  • <iostream>: Defines standard input/output objects (cin, cout, cerr, clog).
  • <fstream>: Supports file input/output (ifstream, ofstream, fstream).
  • <sstream>: Supports string input/output (istringstream, ostringstream).

Basic Operations

#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    // Standard output (cout)
    std::cout << "Hello, C++ STL!" << std::endl;

    // Standard input (cin)
    int x;
    std::cout << "Enter an integer: ";
    std::cin >> x;
    std::cout << "You entered: " << x << std::endl;

    // File output (ofstream)
    std::ofstream out("test.txt");
    out << "Write to file: " << x << std::endl;
    out.close();

    // File input (ifstream)
    std::ifstream in("test.txt");
    std::string line;
    while (std::getline(in, line)) {
        std::cout << "Read from file: " << line << std::endl;
    }
    in.close();

    // String stream (stringstream)
    std::stringstream ss;
    ss << "Value: " << x << ", String: C++";
    std::string str = ss.str();
    std::cout << str << std::endl;

    return 0;
}

Formatted Input/Output

Control formatting using manipulators from the iomanip header file:

#include <iomanip>

int main() {
    int num = 123;
    double pi = 3.1415926;

    // Width and fill
    std::cout << "Width 10, fill 0: " << std::setw(10) << std::setfill('0') << num << std::endl;  // 0000000123

    // Precision control (floating-point)
    std::cout << "Precision 5: " << std::setprecision(5) << pi << std::endl;  // 3.1416

    // Scientific notation
    std::cout << "Scientific notation: " << std::scientific << pi << std::endl;  // 3.14159e+00

    return 0;
}

Containers

Containers are the core components in STL for storing and managing data, categorized into sequence containers, associative containers, unordered containers, and adapters.

Sequence Containers

Sequence containers store data in the order of insertion, supporting random or sequential access.

ContainerFeaturesUse Cases
std::vectorDynamic array, random access O(1), tail insertion/deletion O(1), middle insertion/deletion O(n)Frequent random access, large data changes
std::listDoubly linked list, insertion/deletion O(1) (with iterator), random access O(n)Frequent insertion/deletion, minimal random access
std::dequeDouble-ended queue, head/tail insertion/deletion O(1), random access O(1)Needs double-ended operations, similar to queue/stack

Example: Using vector

#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec = {1, 2, 3};
    vec.push_back(4);  // Tail insertion
    vec.insert(vec.begin() + 1, 5);  // Insert 5 at position 1 → {1,5,2,3,4}

    for (int num : vec) {
        std::cout << num << " ";  // Output: 1 5 2 3 4
    }
    return 0;
}

Associative Containers

Associative containers store elements sorted by key, supporting fast lookup (O(log n)).

ContainerFeaturesUse Cases
std::setOrdered set (red-black tree), unique elements, insertion/lookup O(log n)Deduplication, ordered storage
std::multisetOrdered set allowing duplicatesOrdered data with duplicates
std::mapOrdered key-value pairs (red-black tree), unique keys, insertion/lookup O(log n)Key-value mapping, lookup by key
std::multimapOrdered key-value pairs allowing duplicate keysMappings with duplicate keys

Example: Using map

#include <map>
#include <iostream>

int main() {
    std::map<std::string, int> age_map = {{"Alice", 20}, {"Bob", 25}};
    age_map["Charlie"] = 30;  // Insert new key-value pair

    if (age_map.find("Bob") != age_map.end()) {
        std::cout << "Bob's age: " << age_map["Bob"] << std::endl;  // Output: 25
    }

    for (const auto& pair : age_map) {
        std::cout << pair.first << ": " << pair.second << std::endl;  // Output in ascending key order
    }
    return 0;
}

Unordered Containers (C++11+)

Unordered containers use hash tables, with average insertion/lookup time complexity O(1) (worst case O(n)).

ContainerFeaturesUse Cases
std::unordered_setUnordered set (hash table), unique elementsFast deduplication, unordered storage
std::unordered_mapUnordered key-value pairs (hash table), unique keysFast key-value lookup

Container Adapters

Adapters wrap other containers to provide specific interfaces, simplifying code.

AdapterUnderlying ContainerFeatures
std::stackdeque (default)Last In First Out (LIFO), supports push, pop, top
std::queuedeque (default)First In First Out (FIFO), supports push, pop, front, back
std::priority_queuevector (default)Priority queue (max/min heap), supports push, pop, top (max/min element)

Example: Using priority_queue

#include <queue>
#include <iostream>

int main() {
    // Max heap (default, less comparator)
    std::priority_queue<int> max_heap;
    max_heap.push(3);
    max_heap.push(1);
    max_heap.push(4);
    std::cout << "Heap top (max element): " << max_heap.top() << std::endl;  // 4

    // Min heap (custom greater comparator)
    std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;
    min_heap.push(3);
    min_heap.push(1);
    min_heap.push(4);
    std::cout << "Heap top (min element): " << min_heap.top() << std::endl;  // 1

    return 0;
}

Algorithms

The STL algorithm library provides about 100 generic algorithms covering sorting, searching, traversal, numerical computation, etc. All algorithms operate via iterators, decoupled from specific containers.

Common Algorithm Categories

CategoryExample AlgorithmsComplexity
Non-modifying sequencesfor_each (traversal), find (search), count (count), all_of (all satisfy)O(n)
Modifying sequencescopy (copy), swap (swap), reverse (reverse), sort (sort)O(n)~O(n log n)
Numerical algorithmsaccumulate (sum), inner_product (inner product), partial_sum (partial sum)O(n)

Example: Sorting and Searching

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> nums = {3, 1, 4, 1, 5, 9};

    // Sort (ascending by default)
    std::sort(nums.begin(), nums.end());
    for (int num : nums) {
        std::cout << num << " ";  // Output: 1 1 3 4 5 9
    }

    // Find element 4 (returns iterator)
    auto it = std::find(nums.begin(), nums.end(), 4);
    if (it != nums.end()) {
        std::cout << "\nFound element: " << *it << " (position: " << it - nums.begin() << ")" << std::endl;
    }

    // Count occurrences of 1
    int count = std::count(nums.begin(), nums.end(), 1);
    std::cout << "Count of 1: " << count << std::endl;  // Output: 2

    return 0;
}

Customizing Algorithm Behavior

Pass function objects (functors) or lambda expressions to customize comparison or operation logic:

#include <algorithm>
#include <vector>
#include <iostream>

int main() {
    std::vector<std::string> words = {"apple", "banana", "cherry"};

    // Sort by string length (using lambda)
    std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
        return a.size() < b.size();
    });

    for (const auto& word : words) {
        std::cout << word << " ";  // Output: apple banana cherry (lengths 5,6,6)
    }

    return 0;
}

String Handling

STL provides the std::string class, encapsulating basic string operations and integrating with algorithms for complex processing.

std::string Core Operations

OperationExample
Construction and assignmentstd::string s1 = "hello"; std::string s2(s1); s3 = s2 + " world";
Character accesss[0] (random access, O(1)), s.at(0) (with bounds checking)
Length and capacitys.size() (length), s.capacity() (capacity), s.empty() (check empty)
Modifications.append("!") (append), s.replace(0, 2, "hi") (replace), s.erase(0, 1) (erase)
Search and replaces.find("world") (find substring), s.substr(6, 5) (extract substring)

Strings with Algorithms

Use algorithms like std::transform, std::remove_if for batch string processing:

#include <algorithm>
#include <string>
#include <cctype>
#include <iostream>

int main() {
    std::string text = "Hello, C++ STL!";
    std::cout << "Original string: " << text << std::endl;

    // Convert to uppercase (using transform)
    std::transform(text.begin(), text.end(), text.begin(), ::toupper);
    std::cout << "Uppercase: " << text << std::endl;  // HELLO, C++ STL!

    // Remove punctuation (using remove_if + erase)
    text.erase(std::remove_if(text.begin(), text.end(), ::ispunct), text.end());
    std::cout << "Punctuation removed: " << text << std::endl;  // HELLO C STL

    return 0;
}

Smart Pointers

Smart pointers, introduced in C++11, are memory management tools that automatically manage dynamic memory via RAII (Resource Acquisition Is Initialization), preventing memory leaks.

Comparison of Three Smart Pointers

Smart PointerFeaturesUse Cases
std::unique_ptrExclusive ownership, non-copyable (movable), lightweight (no overhead)Single owner, no sharing
std::shared_ptrShared ownership via reference counting, copyable/movableMultiple owners sharing resources
std::weak_ptrWeak reference (no reference counting), solves shared_ptr circular referencesBreak circular references

Example: unique_ptr and shared_ptr

#include <memory>
#include <iostream>

class MyClass {
public:
    MyClass(int val) : value(val) { std::cout << "Construct: " << value << std::endl; }
    ~MyClass() { std::cout << "Destruct: " << value << std::endl; }
    int value;
};

int main() {
    // unique_ptr: exclusive ownership
    std::unique_ptr<MyClass> uptr(new MyClass(10));
    // std::unique_ptr<MyClass> uptr2 = uptr;  // Error: non-copyable
    std::unique_ptr<MyClass> uptr2 = std::move(uptr);  // Move ownership

    // shared_ptr: shared ownership
    std::shared_ptr<MyClass> sptr1 = std::make_shared<MyClass>(20);  // Recommended: direct construction
    std::shared_ptr<MyClass> sptr2 = sptr1;  // Copy, reference count +1
    std::cout << "Reference count: " << sptr1.use_count() << std::endl;  // Output: 2

    // weak_ptr: weak reference
    std::weak_ptr<MyClass> wptr = sptr1;
    if (auto locked = wptr.lock()) {  // Lock to shared_ptr
        std::cout << "weak_ptr points to valid object, value: " << locked->value << std::endl;
    }

    return 0;
}

Output:

Construct: 10
Destruct: 10
Construct: 20
Reference count: 2
weak_ptr points to valid object, value: 20
Destruct: 20

Iterators and Ranges

Iterators are STL’s “generic pointers” for traversing container elements; C++20’s Ranges library further simplifies iterator usage.

Iterator Categories

Iterator TypeFunctionalitySupported Operations
Input iteratorRead-only, forward traversal (e.g., istream_iterator)++, *, ==, !=
Output iteratorWrite-only, forward traversal (e.g., ostream_iterator)++, *
Forward iteratorRead/write, forward traversal (e.g., forward_list iterator)++, *, -- (partial)
Bidirectional iteratorRead/write, bidirectional traversal (e.g., list, set iterator)++, --, *
Random access iteratorRead/write, random access (e.g., vector, deque iterator)+n, -n, [], <=, >=

Ranges Library (C++20)

The Ranges library in std::ranges encapsulates iterator begin/end into std::ranges::range objects, supporting concise loops and algorithm calls.

Example: Range Traversal and Filtering

#include <ranges>
#include <vector>
#include <iostream>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5, 6};

    // Filter even numbers (using ranges::filter_view)
    auto even_view = nums | std::views::filter([](int x) { return x % 2 == 0; });

    // Traverse range (no explicit iterators)
    for (int num : even_view) {
        std::cout << num << " ";  // Output: 2 4 6
    }

    // Convert to vector (using ranges::to)
    auto even_vec = even_view | std::views::to<std::vector>();
    for (int num : even_vec) {
        std::cout << num << " ";  // Output: 2 4 6
    }

    return 0;
}

Generic Programming

Generic programming is a core C++ design philosophy, using templates to achieve code generality and avoid redundant logic.

Function Templates

Function templates define functions operable on multiple types, instantiated automatically by the compiler based on argument types.

#include <iostream>

// Function template: swap two values
template <typename T>
void swap(T& a, T& b) {
    T temp = std::move(a);
    a = std::move(b);
    b = std::move(temp);
}

int main() {
    int x = 10, y = 20;
    swap(x, y);
    std::cout << "x=" << x << ", y=" << y << std::endl;  // Output: x=20, y=10

    double a = 3.14, b = 6.28;
    swap(a, b);
    std::cout << "a=" << a << ", b=" << b << std::endl;  // Output: a=6.28, b=3.14

    return 0;
}

Class Templates

Class templates define classes operable on multiple types, instantiated with specific types.

#include <iostream>
#include <vector>

// Class template: dynamic array wrapper
template <typename T>
class MyVector {
private:
    std::vector<T> data;
public:
    void push_back(const T& val) {
        data.push_back(val);
    }

    T& operator[](size_t index) {
        return data[index];
    }

    size_t size() const {
        return data.size();
    }
};

int main() {
    MyVector<int> int_vec;
    int_vec.push_back(1);
    int_vec.push_back(2);
    std::cout << "int_vec[1] = " << int_vec[1] << std::endl;  // Output: 2

    MyVector<std::string> str_vec;
    str_vec.push_back("hello");
    str_vec.push_back("world");
    std::cout << "str_vec[0] = " << str_vec[0] << std::endl;  // Output: hello

    return 0;
}

Template Parameters

  • Type Parameters: Declared with typename or class (e.g., template <typename T>).
  • Non-Type Parameters: Declared with concrete types (e.g., template <int N>).
  • Template Template Parameters: The parameter itself is a template (e.g., template <template <typename> class Container>).

File Operations

STL supports file operations via <fstream>, including text and binary file reading/writing.

File Read/Write Process

  1. Open file: Create ifstream (read), ofstream (write), or fstream (read/write) objects, specifying open modes (e.g., ios::in, ios::out, ios::binary).
  2. Check open status: Use is_open() to verify successful opening.
  3. Read/write data: Use <<, >> or read, write methods.
  4. Close file: Call close() to release resources (destructor calls automatically).

Example: Binary File Read/Write

#include <fstream>
#include <iostream>
#include <vector>

struct Student {
    std::string name;
    int age;
};

int main() {
    // Write binary file
    std::ofstream out("students.bin", std::ios::binary | std::ios::out);
    if (!out.is_open()) {
        std::cerr << "Cannot open file for writing" << std::endl;
        return 1;
    }

    std::vector<Student> students = {{"Alice", 20}, {"Bob", 25}};
    size_t count = students.size();
    out.write(reinterpret_cast<const char*>(&count), sizeof(count));  // Write count
    for (const auto& s : students) {
        size_t name_len = s.name.size();
        out.write(reinterpret_cast<const char*>(&name_len), sizeof(name_len));  // Write name length
        out.write(s.name.data(), name_len);  // Write name content
        out.write(reinterpret_cast<const char*>(&s.age), sizeof(s.age));  // Write age
    }
    out.close();

    // Read binary file
    std::ifstream in("students.bin", std::ios::binary | std::ios::in);
    if (!in.is_open()) {
        std::cerr << "Cannot open file for reading" << std::endl;
        return 1;
    }

    size_t read_count;
    in.read(reinterpret_cast<char*>(&read_count), sizeof(read_count));
    std::vector<Student> read_students;
    for (size_t i = 0; i < read_count; ++i) {
        size_t name_len;
        in.read(reinterpret_cast<char*>(&name_len), sizeof(name_len));
        std::string name(name_len, '\0');
        in.read(&name[0], name_len);
        int age;
        in.read(reinterpret_cast<char*>(&age), sizeof(age));
        read_students.push_back({name, age});
    }
    in.close();

    // Output read results
    for (const auto& s : read_students) {
        std::cout << "Name: " << s.name << ", Age: " << s.age << std::endl;  // Output: Alice 20, Bob 25
    }

    return 0;
}

Time and Date

C++ provides <chrono> (C++11+) and <ctime> (C-style) time libraries; <chrono> is modern and type-safe, recommended.

<chrono> Library Core Components

ComponentDescription
std::chrono::durationRepresents time duration (e.g., 5 seconds, 10 minutes), templated with Rep (numeric type) and Period (time unit)
std::chrono::time_pointRepresents a point in time, based on clock and duration
std::chrono::clockClock types (e.g., system_clock system time, steady_clock monotonic clock)

Example: Time Measurement

#include <chrono>
#include <iostream>
#include <thread>  // For simulating time-consuming operations

int main() {
    using namespace std::chrono;

    // Measure function execution time
    auto start = steady_clock::now();

    // Simulate time-consuming operation (sleep 1 second)
    std::this_thread::sleep_for(seconds(1));

    auto end = steady_clock::now();
    auto duration = duration_cast<milliseconds>(end - start);

    std::cout << "Operation took: " << duration.count() << " milliseconds" << std::endl;  // Output: 1000 milliseconds

    return 0;
}

Error Handling

C++ provides multiple error handling mechanisms: exceptions, error codes, and assertions; choose based on the scenario.

Exception Handling

Use try, catch, throw to catch and handle runtime errors, suitable for severe errors unhandleable via return values.

#include <iostream>
#include <stdexcept>  // Standard exception classes

double divide(double a, double b) {
    if (b == 0) {
        throw std::invalid_argument("Divisor cannot be 0");  // Throw exception
    }
    return a / b;
}

int main() {
    try {
        double result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;  // Output: Error: Divisor cannot be 0
    } catch (...) {
        std::cerr << "Unknown error" << std::endl;
    }

    return 0;
}

Error Codes

Return std::error_code or errno (C-style) to indicate errors, suitable for silent error handling.

#include <iostream>
#include <system_error>  // std::error_code

std::error_code open_file(const std::string& path) {
    // Simulate file open failure (error code EINVAL: invalid argument)
    return std::make_error_code(std::errc::invalid_argument);
}

int main() {
    auto ec = open_file("nonexistent.txt");
    if (ec) {
        std::cerr << "Error: " << ec.message() << std::endl;  // Output: Error: Invalid argument
    }
    return 0;
}

Assertions

Use the assert macro to check conditions during debugging; terminates program if condition fails, for catching logic errors.

#include <cassert>
#include <iostream>

int main() {
    int x = 10;
    assert(x > 0 && "x must be greater than 0");  // Condition satisfied, no trigger
    // assert(x < 0 && "x must be less than 0");  // Condition fails, triggers assertion failure
    return 0;
}

Concurrency

C++11 introduced the standard concurrency library <thread> for multithreading; C++20 added coroutines to simplify asynchronous programming.

Multithreading Basics

#include <thread>
#include <iostream>
#include <mutex>  // Mutex

std::mutex mtx;  // Protects shared resources

void print_message(const std::string& msg) {
    std::lock_guard<std::mutex> lock(mtx);  // Automatic lock/unlock
    std::cout << msg << std::endl;
}

int main() {
    std::thread t1(print_message, "Thread 1: Hello");
    std::thread t2(print_message, "Thread 2: World");

    t1.join();  // Wait for thread 1 to finish
    t2.join();  // Wait for thread 2 to finish

    return 0;
}

Mutexes and Condition Variables

  • Mutex (std::mutex): Protects shared resources, avoids race conditions.
  • Condition Variable (std::condition_variable): Synchronizes threads, waits for specific conditions.
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <queue>

std::mutex mtx;
std::condition_variable cv;
std::queue<int> data_queue;
bool data_ready = false;

void producer() {
    for (int i = 0; i < 5; ++i) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::lock_guard<std::mutex> lock(mtx);
        data_queue.push(i);
        data_ready = true;
        cv.notify_one();  // Notify consumer
    }
}

void consumer() {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, []{ return data_ready; });  // Wait for data ready
        if (data_queue.empty()) break;
        int data = data_queue.front();
        data_queue.pop();
        std::cout << "Consumed data: " << data << std::endl;
        data_ready = false;
    }
}

int main() {
    std::thread prod(producer);
    std::thread cons(consumer);
    prod.join();
    cons.join();
    return 0;
}

Coroutines (C++20)

Coroutines are lightweight user-space threads, supporting asynchronous programming and avoiding callback hell.

#include <coroutine>
#include <iostream>

// Coroutine return object (Promise type)
struct Task {
    struct promise_type {
        Task get_return_object() { return {}; }
        std::suspend_never initial_suspend() { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }
    };
};

Task my_coroutine() {
    std::cout << "Coroutine started" << std::endl;
    co_await std::suspend_always{};  // Suspend coroutine
    std::cout << "Coroutine resumed" << std::endl;
}

int main() {
    auto coro = my_coroutine();
    // Resume coroutine (requires manual scheduling; real use needs a scheduler)
    return 0;
}

Dynamic Memory Management

Dynamic memory management involves manual allocation/deallocation (new/delete) and smart pointers (as described earlier); avoid memory leaks and dangling pointers.

Manual Memory Management

#include <iostream>

class MyClass {
public:
    MyClass() { std::cout << "Construct" << std::endl; }
    ~MyClass() { std::cout << "Destruct" << std::endl; }
};

int main() {
    // Manual allocation
    MyClass* ptr = new MyClass();
    // Use memory...
    delete ptr;  // Manual deallocation

    // Array allocation
    int* arr = new int[5]{1, 2, 3, 4, 5};
    delete[] arr;  // Deallocate array

    return 0;
}

Memory Pool

A memory pool pre-allocates large memory blocks, reducing new/delete calls, improving performance (suitable for frequent small object creation/destruction).

Function Objects (Functors) and Variadic Templates

Function Objects (Functors)

Function objects are classes or structs overloading operator(), usable as predicates or callbacks in algorithms.

#include <algorithm>
#include <vector>
#include <iostream>

// Function object: check even
struct IsEven {
    bool operator()(int x) const {
        return x % 2 == 0;
    }
};

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    int count = std::count_if(nums.begin(), nums.end(), IsEven());
    std::cout << "Even count: " << count << std::endl;  // Output: 2
    return 0;
}

Variadic Templates (C++11+)

Variadic templates allow functions or classes to accept arbitrary numbers of parameters, supporting parameter pack expansion.

#include <iostream>

// Base case: 0 parameters
void print() {
    std::cout << "End" << std::endl;
}

// Recursive case: n parameters
template <typename T, typename... Args>
void print(const T& first, const Args&... rest) {
    std::cout << first << " ";
    print(rest...);  // Expand parameter pack
}

int main() {
    print(1, "hello", 3.14, "world");  // Output: 1 hello 3.14 world End
    return 0;
}

Template Metaprogramming (TMP)

Template metaprogramming uses templates for compile-time computation, enabling type deduction and compile-time numerical calculations.

Compile-Time Numerical Computation

#include <iostream>

// Compile-time factorial (template specialization)
template <int N>
struct Factorial {
    static constexpr int value = N * Factorial<N - 1>::value;
};

template <>
struct Factorial<0> {
    static constexpr int value = 1;
};

int main() {
    constexpr int fact_5 = Factorial<5>::value;  // Compile-time compute 5!
    std::cout << "5 factorial: " << fact_5 << std::endl;  // Output: 120
    return 0;
}

C++20 New Features

C++20 is a major update, introducing modern features to improve expressiveness and safety.

Core New Features

FeatureDescription
RangesSimplify iterator operations, support pipeline data processing (e.g., views::filter, views::map)
CoroutinesLightweight asynchronous programming, support co_await, co_yield, co_return
ConceptsConstrain template parameters, improve error message readability (e.g., std::integral, std::sortable)
ModulesReplace header files, improve compilation speed and encapsulation
Three-way comparison (<=>)Unified comparison operators (==, !=, <, > etc.), auto-generate comparison logic
constexpr enhancementsAllow constexpr functions to use more features (e.g., dynamic allocation, virtual functions)
std::formatType-safe string formatting (replaces sprintf)

Example: Three-way Comparison and Ranges

#include <compare>
#include <ranges>
#include <vector>
#include <iostream>

int main() {
    // Three-way comparison (<=>)
    int a = 10, b = 20;
    auto cmp = a <=> b;  // Type: std::strong_ordering
    if (cmp < 0) {
        std::cout << "a < b" << std::endl;  // Output: a < b
    }

    // Range filtering and transformation
    std::vector<int> nums = {1, 2, 3, 4, 5};
    auto even_sq = nums 
        | std::views::filter([](int x) { return x % 2 == 0; })
        | std::views::transform([](int x) { return x * x; });

    for (int x : even_sq) {
        std::cout << x << " ";  // Output: 4 16
    }

    return 0;
}

Summary and Practice

Key Summary

  • Standard library is C++ core: Covers input/output, data structures, algorithms, memory management, etc., for nearly all scenarios.
  • Containers and algorithms decoupled: Containers store data, algorithms operate on data via iterators, enhancing reusability.
  • Smart pointers manage memory: Prefer unique_ptr (exclusive) and shared_ptr (shared), avoid manual new/delete.
  • C++20 boosts productivity: Ranges, coroutines, concepts simplify complex logic.

Practice

  • Prefer standard library: Avoid reinventing the wheel, use optimized containers and algorithms.
  • Learn iterators and ranges: Master iterator categories and ranges for concise code.
  • Use smart pointers appropriately: Choose unique_ptr or shared_ptr based on ownership, avoid circular references.
  • Stay updated with C++ standards: Learn C++20/23 features to improve code quality and efficiency.

By deeply mastering the C++ standard library, developers can write efficient, robust, and maintainable code for applications ranging from embedded systems to large-scale software.

Share your love