### Generating Random Numbers (Die Roll) in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Demonstrates the use of modern C++ random number generation facilities to produce random integers with a uniform distribution. This example specifically shows how to simulate rolling a six-sided die. ```cpp #include int main() { std::random_device random_device; // Non-deterministic source std::mt19937 random_engine{random_device()}; // Mersenne Twister std::uniform_int_distribution die_distribution{1, 6}; int die_roll = die_distribution(random_engine); // die_roll is random integer from 1 to 6 // Generate more random numbers int another_roll = die_distribution(random_engine); } ``` -------------------------------- ### Measuring Execution Time in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Explains how to measure the execution time of code segments in C++ using the `std::chrono` library. It utilizes `steady_clock` to get time points before and after the code execution and calculates the duration. ```cpp #include int main() { using clock = std::chrono::steady_clock; clock::time_point start = clock::now(); // A long task... clock::time_point end = clock::now(); clock::duration execution_time = end - start; // Access value with count(), cast to different units as needed auto ms = std::chrono::duration_cast(execution_time); } ``` -------------------------------- ### Reading Input Streams Line-by-Line in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Shows how to process the contents of an input stream line-by-line using `std::getline` within a while loop. This method is versatile and works with various input streams like `std::cin`, file streams, and string streams. ```cpp #include #include int main() { std::istringstream stream{"This stream\n" "contains many\n" "lines.\n"}; std::string line; while (std::getline(stream, line)) { // Process each line // Works with std::cin, file streams, etc. } } ``` -------------------------------- ### Perfect Forwarding Arguments in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Demonstrates how to forward function arguments while preserving their value category (lvalue/rvalue) and cv-qualifiers using forwarding references and `std::forward`. This is useful for creating wrappers or forwarding functions. ```cpp #include template std::pair make_pair_wrapper(T&& t, U&& u) { // Forward arguments with their original value category return std::make_pair(std::forward(t), std::forward(u)); } int main() { // Works with both lvalues and rvalues std::pair p1{ make_pair_wrapper(1, 2) }; int x = 1, y = 2; std::pair p2{ make_pair_wrapper(x, y) }; } ``` -------------------------------- ### Returning Multiple Values from a Function in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Illustrates how to return multiple values from a C++ function using `std::tuple` and structured bindings (available since C++17). This avoids the need for output parameters or custom structs for simple return types. ```cpp #include std::tuple foo() { return {128, true, 1.5f}; } int main() { // Method 1: Store tuple and access elements std::tuple result = foo(); int value = std::get<0>(result); // value = 128 // Method 2: Structured binding (C++17) auto [value1, value2, value3] = foo(); // value1 = 128, value2 = true, value3 = 1.5f } ``` -------------------------------- ### Sort Range of Elements in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Illustrates sorting elements within a range in ascending or descending order using std::sort. It shows the default ascending sort and how to use std::greater for descending order. ```cpp #include #include #include int main() { std::array arr = {3, 4, 1, 5, 2}; // Sort in ascending order (default) std::sort(std::begin(arr), std::end(arr)); // Result: {1, 2, 3, 4, 5} // Sort in descending order using std::greater std::sort(std::begin(arr), std::end(arr), std::greater{}); // Result: {5, 4, 3, 2, 1} } ``` -------------------------------- ### Copy Range of Elements in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Demonstrates how to copy elements from a source range to a target container using iterators, std::copy, or std::back_inserter for dynamic insertion. This pattern is useful for transferring data between containers or initializing new ones. ```cpp #include #include #include std::vector target2(5); std::vector target3; template void foo(RangeOfInts source) { // Method 1: Copy via constructor with iterators std::vector target1{std::begin(source), std::end(source)}; // Method 2: Copy into pre-allocated container std::copy(std::begin(source), std::end(source), std::begin(target2)); // Method 3: Copy with dynamic insertion std::copy(std::begin(source), std::end(source), std::back_inserter(target3)); } int main() { std::vector vec = {5, 4, 3, 2, 1}; foo(vec); } ``` -------------------------------- ### Visitor Pattern in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Illustrates the Visitor pattern in C++. This pattern enables adding new operations to existing object structures without modifying them. It utilizes double dispatch to apply operations based on both element and visitor types. ```cpp class element_concrete_1; class element_concrete_2; class visitor { public: virtual void visit(element_concrete_1& el) = 0; virtual void visit(element_concrete_2& el) = 0; }; class visitor_concrete : public visitor { public: virtual void visit(element_concrete_1& el) override { /* Process el */ } virtual void visit(element_concrete_2& el) override { /* Process el */ } }; class element { public: virtual void accept(visitor& v) = 0; }; class element_concrete_1 : public element { public: virtual void accept(visitor& v) override { v.visit(*this); } }; class element_concrete_2 : public element { public: virtual void accept(visitor& v) override { v.visit(*this); } }; int main() { element_concrete_1 x; element_concrete_2 y; element& el1 = x; element& el2 = y; visitor_concrete v; el1.accept(v); // Calls visit(element_concrete_1&) el2.accept(v); // Calls visit(element_concrete_2&) } ``` -------------------------------- ### Builder Pattern Implementation in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Showcases the Builder design pattern in C++. It uses a nested `builder` class to construct complex `foo` objects step-by-step through a fluent interface, allowing for flexible object creation. ```cpp #include class foo { public: class builder; foo(int prop1, bool prop2, bool prop3, std::vector prop4) : prop1{prop1}, prop2{prop2}, prop3{prop3}, prop4{prop4} { } int prop1; bool prop2; bool prop3; std::vector prop4; }; class foo::builder { public: builder& set_prop1(int value) { prop1 = value; return *this; } builder& set_prop2(bool value) { prop2 = value; return *this; } builder& set_prop3(bool value) { prop3 = value; return *this; } builder& set_prop4(std::vector value) { prop4 = value; return *this; } foo build() const { return foo{prop1, prop2, prop3, prop4}; } private: int prop1 = 0; bool prop2 = false; bool prop3 = false; std::vector prop4 = {}; }; int main() { foo f = foo::builder{}.set_prop1(5) .set_prop3(true) .build(); } ``` -------------------------------- ### Virtual Constructor for Polymorphic Cloning (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Clones objects polymorphically through a base class pointer using a virtual `clone()` method. This pattern allows for creating copies of objects without knowing their concrete type at compile time, which is useful in factory patterns and object serialization. ```cpp #include class Base { public: virtual ~Base() {} virtual Base* clone() const = 0; }; class Derived : public Base { public: Derived* clone() const override { return new Derived(*this); } }; void foo(std::unique_ptr original) { // Create a copy through the base pointer std::unique_ptr copy{original->clone()}; } int main() { std::unique_ptr p = std::make_unique(); foo(std::move(p)); } ``` -------------------------------- ### Rule of Five Class Design in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Details the Rule of Five for manual resource management in C++ RAII classes. It requires defining the copy constructor, copy assignment operator, move constructor, move assignment operator, and destructor. ```cpp #include class resource { int x = 0; }; class foo { public: foo() : p{new resource{}} { } // Copy constructor foo(const foo& other) : p{new resource{*(other.p)}} { } // Move constructor foo(foo&& other) : p{other.p} { other.p = nullptr; } // Copy assignment operator foo& operator=(const foo& other) { if (&other != this) { delete p; p = nullptr; p = new resource{*(other.p)}; } return *this; } // Move assignment operator foo& operator=(foo&& other) { if (&other != this) { delete p; p = other.p; other.p = nullptr; } return *this; } // Destructor ~foo() { delete p; } private: resource* p; }; int main() { foo f1; foo f2 = f1; // Copy foo f3 = std::move(f1); // Move } ``` -------------------------------- ### Decorator Pattern in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Demonstrates the Decorator pattern in C++. This pattern allows adding new responsibilities to objects dynamically by wrapping them in decorator classes. It uses inheritance and composition to achieve this. ```cpp class foo { public: virtual void do_work() = 0; }; class foo_concrete : public foo { public: virtual void do_work() override { /* Original work */ } }; class foo_decorator : public foo { public: foo_decorator(foo& f) : f(f) { } virtual void do_work() override { // Add behavior before/after f.do_work(); // Delegate to wrapped object } private: foo& f; }; int main() { foo_concrete f; foo_decorator decorated_f{f}; decorated_f.do_work(); // Decorated behavior } ``` -------------------------------- ### Remove Elements from Container in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Demonstrates the erase-remove idiom for efficiently removing elements from standard C++ containers. It covers removing elements by value and by a custom predicate. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4, 2, 5, 2, 6}; // Remove all occurrences of value 2 v.erase(std::remove(std::begin(v), std::end(v), 2), std::end(v)); // Result: {1, 3, 4, 5, 6} // Remove all even numbers using a predicate v.erase(std::remove_if(std::begin(v), std::end(v), [](int i) { return i%2 == 0; }), std::end(v)); // Result: {1, 3, 5} } ``` -------------------------------- ### Observer Pattern Implementation in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Provides a C++ implementation of the Observer design pattern. It defines an abstract `observer` class and a `subject` class that manages a collection of observers, notifying them when an event occurs. ```cpp #include #include class observer { public: virtual void notify() = 0; }; class observer_concrete : public observer { public: virtual void notify() override { /* Handle notification */ } }; class subject { public: void register_observer(observer& o) { observers.push_back(o); } void notify_observers() { for (observer& o : observers) { o.notify(); } } private: std::vector> observers; }; int main() { subject s; observer_concrete o1, o2; s.register_observer(o1); s.register_observer(o2); s.notify_observers(); // Both o1 and o2 receive notification } ``` -------------------------------- ### Execute Task Asynchronously with std::async (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Uses `std::async` for high-level asynchronous execution with automatic result handling via `std::future`. This simplifies asynchronous programming by managing thread creation and result retrieval. ```cpp #include int func() { int some_value = 0; // Do work... return some_value; } int main() { // Launch async task std::future result_future = std::async(func); // Do other work concurrently... // Block until result is available int result = result_future.get(); } ``` -------------------------------- ### Create a Thread with std::thread (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Executes code on a separate thread using `std::thread`, passing arguments by value or by reference with `std::ref`. This is the fundamental way to achieve concurrency in C++ by launching new threads of execution. ```cpp #include #include #include void func(std::string str, int& x) { // Process str and modify x } void do_something() { } int main() { std::string str = "Test"; int x = 5; // Create thread with function and arguments // Use std::ref for reference parameters std::thread t{func, str, std::ref(x)}; do_something(); // Runs concurrently with func t.join(); // Wait for thread to complete } ``` -------------------------------- ### PIMPL Idiom for Implementation Hiding (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Hides implementation details to reduce compilation dependencies and improve compile times by using a pointer to an implementation class. This pattern separates the interface from the implementation, allowing changes to the implementation without affecting users of the class. ```cpp // foo.h - header file #include class foo { public: foo(); ~foo(); foo(foo&&); foo& operator=(foo&&); private: class impl; std::unique_ptr pimpl; }; // foo.cpp - implementation file class foo::impl { public: void do_internal_work() { internal_data = 5; } private: int internal_data = 0; }; foo::foo() : pimpl{std::make_unique()} { pimpl->do_internal_work(); } foo::~foo() = default; foo::foo(foo&&) = default; foo& foo::operator=(foo&&) = default; int main() { foo f; } ``` -------------------------------- ### Copy-and-Swap Idiom for Assignment Operators (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Implements assignment operators with strong exception safety by leveraging copy/move constructors and a swap function. This pattern ensures that assignment operations are exception-safe, meaning they either complete successfully or leave the object in a valid state. ```cpp #include class resource { int x = 0; }; class foo { public: foo() : p{new resource{}} { } foo(const foo& other) : p{new resource{*(other.p)}} { } foo(foo&& other) : p{other.p} { other.p = nullptr; } // Single assignment operator handles both copy and move foo& operator=(foo other) { swap(*this, other); return *this; } ~foo() { delete p; } friend void swap(foo& first, foo& second) { using std::swap; swap(first.p, second.p); } private: resource* p; }; int main() { foo f1, f2, f3; f2 = f1; // Copy assignment via copy-and-swap f3 = std::move(f1); // Move assignment via copy-and-swap swap(f2, f3); // ADL-enabled swap } ``` -------------------------------- ### Rule of Zero Class Design in C++ Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Explains the Rule of Zero, which advocates for avoiding custom copy/move operations and destructors by leveraging value semantics of existing types. This allows the compiler to generate default special member functions. ```cpp #include #include class foo { private: int x = 10; std::vector v = {1, 2, 3, 4, 5}; // No custom copy/move/destructor needed - compiler generates them }; class bar { public: std::unique_ptr p = std::make_unique(5); // Not copyable (unique_ptr), but movable automatically }; int main() { foo f1; foo f2 = f1; // Copy works automatically bar b1; bar b2 = std::move(b1); // Move works automatically } ``` -------------------------------- ### Shared Ownership with std::shared_ptr (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Shares ownership of dynamically allocated objects between multiple owners using `std::shared_ptr`. This smart pointer uses reference counting to manage object lifetime, ensuring the object is deallocated only when all shared pointers to it are destroyed. ```cpp #include struct foo {}; void func(std::shared_ptr obj) { // func shares ownership with main } int main() { std::shared_ptr obj = std::make_shared(); func(obj); // Share ownership (copy, not move) // obj is still valid - both main and func own the object // Object destroyed when all shared_ptrs are destroyed } ``` -------------------------------- ### Unique Ownership with std::unique_ptr (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Transfers unique ownership of dynamically allocated objects using `std::unique_ptr` and `std::move`. This smart pointer ensures that only one owner exists at a time, automatically deallocating the object when the owner goes out of scope. ```cpp #include #include struct foo {}; void func(std::unique_ptr obj) { // func now owns the object } int main() { std::unique_ptr obj = std::make_unique(); func(std::move(obj)); // Transfer ownership to func // obj is now nullptr - main no longer owns the object } ``` -------------------------------- ### Pass Values Between Threads with std::promise/std::future (C++) Source: https://context7.com/sftrabbit/cpppatterns-patterns/llms.txt Employs `std::promise` and `std::future` to communicate values asynchronously between threads. This mechanism allows one thread to set a value that another thread can retrieve later, facilitating inter-thread communication. ```cpp #include #include void func(std::promise result_promise) noexcept { result_promise.set_value(42); // Set the promised value } int main() { std::promise result_promise; std::future result_future = result_promise.get_future(); // Move promise into thread (promises are non-copyable) std::thread t{func, std::move(result_promise)}; // Block until value is available int result = result_future.get(); // result = 42 t.join(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.