### iota_view Deduction Guide Example (C++) Source: https://www.cppreference.com/w/cpp/ranges/iota_view/deduction_guides This C++ code snippet demonstrates the usage of `std::ranges::iota_view` with its deduction guides. It initializes an `iota_view` with a starting value and an ending bound, deducing the template types automatically. The example includes assertions to verify the front and back elements of the generated view. ```cpp #include #include int main() { auto io = std::ranges::iota_view(1L, 7L); // deduces W and Bound as “long” assert(io.front() == 1L && io.back() == 6L); } ``` -------------------------------- ### C++ User-defined Deduction Guide Example Source: https://www.cppreference.com/w/cpp/language/ctad Demonstrates the declaration of a class template with constructors and an additional user-defined deduction guide. It shows how this guide customizes argument deduction for the class template and provides examples of valid and invalid usage scenarios. ```cpp // declaration of the template template struct container { container(T t) {}   template container(Iter beg, Iter end); };   // additional deduction guide template container(Iter b, Iter e) -> container::value_type>;   // uses container c(7); // OK: deduces T=int using an implicitly-generated guide std::vector v = {/* ... */}; auto d = container(v.begin(), v.end()); // OK: deduces T=double container e{5, 6}; // Error: there is no std::iterator_traits::value_type ``` -------------------------------- ### Example Usage of std::unordered_multiset Deduction Guides Source: https://www.cppreference.com/w/cpp/container/unordered_multiset/deduction_guides This C++ example demonstrates how to use the deduction guides for std::unordered_multiset. It shows constructing a multiset from an initializer list and from an iterator range. ```cpp #include int main() { // guide #2 deduces std::unordered_multiset std::unordered_multiset s = {1, 2, 3, 4}; // guide #1 deduces std::unordered_multiset std::unordered_multiset s2(s.begin(), s.end()); } ``` -------------------------------- ### Suggest Trivial Example for std::ranges::iota (C++) Source: https://www.cppreference.com/w/Talk%253Acpp/algorithm/ranges/iota A suggestion for a simpler example to illustrate the basic usage of std::ranges::iota. This example aims to provide a clearer starting point for understanding the function's behavior compared to more complex scenarios. ```cpp std::ranges::iota(l, 0); ``` -------------------------------- ### Simple Ruby Code Example Source: https://www.cppreference.com/w/Template_talk%253Aexample A basic example of Ruby code intended to be run, demonstrating a simple print statement. This snippet is presented within the context of discussing output formatting in documentation examples. ```ruby puts("Some code, with the output provided."); ``` -------------------------------- ### C++ User-Defined Deduction Guide Example Source: https://www.cppreference.com/w/cpp/language/deduction_guide Demonstrates the declaration of a class template with a constructor and an additional user-defined deduction guide. It shows how the deduction guide allows for template argument deduction based on constructor arguments and highlights potential errors. ```cpp // declaration of the template template struct container { container(T t) {}   template container(Iter beg, Iter end); };   // additional deduction guide template container(Iter b, Iter e) -> container::value_type>;   // uses container c(7); // OK: deduces T=int using an implicitly-generated guide std::vector v = {/* ... */}; auto d = container(v.begin(), v.end()); // OK: deduces T=double container e{5, 6}; // Error: there is no std::iterator_traits::value_type ``` -------------------------------- ### C++ Example: Basic File and Directory Copying Source: https://www.cppreference.com/w/cpp/experimental/fs/copy_options Demonstrates the usage of `std::experimental::filesystem::copy` with different options, including creating directories, copying files, copying directories recursively, and cleaning up created files and directories. This example requires the `` header. ```cpp #include #include #include namespace fs = std::experimental::filesystem; int main() { fs::create_directories("sandbox/dir/subdir"); std::ofstream("sandbox/file1.txt").put('a'); fs::copy("sandbox/file1.txt", "sandbox/file2.txt"); // copy file fs::copy("sandbox/dir", "sandbox/dir2"); // copy directory (non-recursive) // sandbox holds 2 files and 2 directories, one of which has a subdirectory // sandbox/file1.txt // sandbox/file2.txt // sandbox/dir2 // sandbox/dir // sandbox/dir/subdir fs::copy("sandbox", "sandbox/copy", fs::copy_options::recursive); // sandbox/copy holds copies of the above files and subdirectories fs::remove_all("sandbox"); } ``` -------------------------------- ### Create and Use Hard Link - C++ Source: https://www.cppreference.com/w/cpp/experimental/fs/create_hard_link Demonstrates how to create a directory, create a regular file, create a hard link to that file, and then read from the file using the hard link. It also shows how to remove the created files and directories. This example requires the `` library. ```cpp #include #include #include namespace fs = std::experimental::filesystem; int main() { fs::create_directories("sandbox/subdir"); std::ofstream("sandbox/a").put('a'); // create regular file fs::create_hard_link("sandbox/a", "sandbox/b"); fs::remove("sandbox/a"); // read from the original file via surviving hard link char c = std::ifstream("sandbox/b").get(); std::cout << c << '\n'; fs::remove_all("sandbox"); } ``` -------------------------------- ### C++ forward_list deduction guides example Source: https://www.cppreference.com/w/cpp/container/forward_list/deduction_guides This example demonstrates the usage of deduction guides for std::forward_list. It shows how explicit and implicit deduction works when initializing a forward_list from iterators. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::forward_list std::forward_list x(v.begin(), v.end()); // deduces std::forward_list::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::forward_list y{v.begin(), v.end()}; } ``` -------------------------------- ### Build QCH Book with qhelpgenerator (Bash) Source: https://www.cppreference.com/w/Cppreference_talk%253AArchives This bash script demonstrates how to rebuild a QCH (Qt Compressed Help) book using the `qhelpgenerator` tool. It involves copying a project file, running the generator, and cleaning up temporary files. Ensure the `output` directory contains the necessary files for processing. ```bash cp qch-help-project.xml output/qch.xml pushd "output"; qhelpgenerator qch.xml -o "../cppreference-doc-en.qch"; popd rm -f output/qch.xml ``` -------------------------------- ### Initialize Qt5 Repository (Bash) Source: https://www.cppreference.com/w/Talk%253Acpp/links/libs This command sequence is used to clone the Qt5 repository and initialize its submodules. It's a prerequisite for analyzing the Qt5 codebase using tools like `cloc`. ```bash git clone git://code.qt.io/qt/qt5.git cd qt5 perl init-repository ``` -------------------------------- ### C++ Hello World Program Source: https://www.cppreference.com/book/intro/hello_world A basic C++ program that prints "Hello World!" to the console. It includes the iostream library for input/output operations and demonstrates the structure of the main function and console output. ```cpp #include int main() { std::cout << "Hello World!\n"; return 0; } ``` -------------------------------- ### std::shared_ptr Deduction Guides Example (C++17) Source: https://www.cppreference.com/w/cpp/memory/shared_ptr/deduction_guides An example demonstrating the usage of explicit deduction guides for std::shared_ptr when initializing from std::weak_ptr and std::shared_ptr. This snippet requires the header. ```cpp #include int main() { auto p = std::make_shared(42); std::weak_ptr w{p}; // explicit deduction guide is used in this case std::shared_ptr p2{w}; // explicit deduction guide is used in this case } ``` -------------------------------- ### C++ Stack Deduction Guide Example Source: https://www.cppreference.com/w/cpp/container/stack/deduction_guides This C++ code snippet demonstrates the use of deduction guides for the std::stack container. It initializes a std::stack directly from a std::vector, allowing the compiler to deduce the appropriate template arguments for the stack, specifically its element type and underlying container type. This feature simplifies stack creation when the underlying container is compatible. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; std::stack s{v}; // guide #1 deduces std::stack> } ``` -------------------------------- ### C++ std::valarray Deduction Guide Example Source: https://www.cppreference.com/w/cpp/numeric/valarray/deduction_guides This example demonstrates the usage of the std::valarray deduction guide in C++17. It shows how to initialize a valarray from a C-style array and a size, allowing for type deduction. The output shows the elements of the initialized valarray. ```cpp #include #include int main() { int a[] = {1, 2, 3, 4}; std::valarray va(a, 3); // uses explicit deduction guide for (int x : va) std::cout << x << ' '; std::cout << '\n'; } ``` -------------------------------- ### C sig_atomic_t Example for Signal Handling Source: https://www.cppreference.com/w/c/program/sig_atomic_t Demonstrates the use of `sig_atomic_t` for safely handling signals in C. It installs a signal handler that updates a `sig_atomic_t` variable and then raises a signal to test the handler. The example shows how the signal status is captured atomically. ```c #include #include volatile sig_atomic_t gSignalStatus = 0; void signal_handler(int status) { gSignalStatus = status; } int main(void) { /* Install a signal handler. */ signal(SIGINT, signal_handler); printf("SignalValue: %d\n", gSignalStatus); printf("Sending signal: %d\n", SIGINT); raise(SIGINT); printf("SignalValue: %d\n", gSignalStatus); } ``` -------------------------------- ### Create Directories Example using C++ Filesystem Source: https://www.cppreference.com/w/cpp/filesystem/create_directory This C++ example demonstrates the basic usage of std::filesystem::create_directories and std::filesystem::create_directory. It shows how to create nested directories, handle cases where a directory already exists, set file permissions, and clean up created directories. The code relies on the `` header and basic C++ standard library features. ```cpp #include #include #include int main() { std::filesystem::current_path(std::filesystem::temp_directory_path()); // Basic usage std::filesystem::create_directories("sandbox/1/2/a"); std::filesystem::create_directory("sandbox/1/2/b"); // Directory already exists (false returned, no error) assert(!std::filesystem::create_directory("sandbox/1/2/b")); // Permissions copying usage std::filesystem::permissions( "sandbox/1/2/b", std::filesystem::perms::others_all, std::filesystem::perm_options::remove ); std::filesystem::create_directory("sandbox/1/2/c", "sandbox/1/2/b"); std::system("ls -l sandbox/1/2"); std::system("tree sandbox"); std::filesystem::remove_all("sandbox"); } ``` -------------------------------- ### C++ std::queue Deduction Guide Example Source: https://www.cppreference.com/w/cpp/container/queue/deduction_guides Demonstrates the use of deduction guides for std::queue in C++23, allowing for template argument deduction when initializing a queue with an initializer list or another container. This example specifically shows constructing a queue from a std::vector. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; std::queue s{v}; // guide #1 deduces std::queue> } ``` -------------------------------- ### C++ std::deque Deduction Guides Example Source: https://www.cppreference.com/w/cpp/container/deque/deduction_guides This C++ code snippet demonstrates the usage of deduction guides for std::deque. It highlights how explicit deduction guides and list initialization can affect the deduced type of a deque, specifically when initializing from iterators of another container like std::vector. The example utilizes standard C++ containers and iterators. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::deque std::deque x(v.begin(), v.end()); // deduces std::deque::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::deque y{v.begin(), v.end()}; } ``` -------------------------------- ### std::clamp example - C++ Source: https://www.cppreference.com/w/cpp/algorithm/clamp An example demonstrating the usage of std::clamp with different integer types and ranges. It includes necessary headers for algorithm, integer types, formatting, and I/O. ```cpp #include #include #include #include   int main() { std::cout << "[raw] " "[" << INT8_MIN << ',' << INT8_MAX << "] " "[0," << UINT8_MAX << "]\n";   for (const int v : {-129, -128, -1, 0, 42, 127, 128, 255, 256}) std::cout << std::setw(4) << v << std::setw(11) << std::clamp(v, INT8_MIN, INT8_MAX) << std::setw(8) << std::clamp(v, 0, UINT8_MAX) << '\n'; } ``` -------------------------------- ### Non-Template Deduction Guides - C++ Source: https://www.cppreference.com/w/cpp/language/ctad Shows an example of a user-defined deduction guide that is not a template. This guide allows deduction for a class template based on a specific constructor signature. ```cpp template struct S { S(T); }; S(char const*) -> S; S s{"hello"}; // deduced to S ``` -------------------------------- ### Basic std::format Usage Example (C++) Source: https://www.cppreference.com/w/cpp/utility/format A simple example demonstrating the basic usage of std::format to create a formatted string. It includes the necessary header and an assertion to verify the output. ```cpp #include #include   int main() { std::string message = std::format("The answer is {}.", 42); assert(message == "The answer is 42."); } ``` -------------------------------- ### Example: Using std::basic_string_view Deduction Guides Source: https://www.cppreference.com/w/cpp/string/basic_string_view/deduction_guides This example demonstrates the usage of `std::basic_string_view` deduction guides with C++20 and C++23 features. It shows how `std::basic_string_view` can deduce its character type from `std::array` using iterator-sentinel pairs and ranges, for `char`, `wchar_t`, and even `long` character types. ```cpp #include #include #include   int main() { std::array a1{'n', 'u', 'c', 'l', 'e', 'o', 'n', 's', ':', '\n'}; std::basic_string_view s1(a1.cbegin(), a1.cend()); // deduction: CharT -> char static_assert(std::is_same_v); std::cout << s1;   std::array a2{L'p', L'r', L'o', L't', L'o', L'n', L's', L'\n'}; std::basic_string_view s2(a2.cbegin(), a2.cend()); // deduction: CharT -> wchar_t static_assert(std::is_same_v); std::wcout << s2;   std::array a3{'n', 'e', 'u', 't', 'r', 'o', 'n', 's', '\n'}; std::basic_string_view s3(a3.cbegin(), a3.cend()); // deduction: CharT -> long static_assert(std::is_same_v); for (const auto e : s3) std::cout << static_cast(e); } ``` -------------------------------- ### C++ Initialization Examples Source: https://www.cppreference.com/w/cpp/language/initialization Demonstrates different forms of initialization in C++, including default, copy, direct, and list initialization for std::string and aggregate initialization for a character array. It also shows reference initialization. ```cpp #include std::string s1; // default-initialization std::string s2(); // NOT an initialization! // actually declares a function “s2” // with no parameter and returns std::string std::string s3 = "hello"; // copy-initialization std::string s4("hello"); // direct-initialization std::string s5{'a'}; // list-initialization (since C++11) char a[3] = {'a', 'b'}; // aggregate initialization // (part of list initialization since C++11) char& c = a[0]; // reference initialization ``` -------------------------------- ### Example: Constructing std::unordered_multimap Source: https://www.cppreference.com/w/cpp/container/unordered_multimap/deduction_guides This C++ example demonstrates how to construct `std::unordered_multimap` using deduction guides. It shows the correct way to initialize a multimap from an initializer list of pairs and from an iterator range. ```cpp #include int main() { // std::unordered_multimap m1 = {{"foo", 1}, {"bar", 2}}; // Error: braced-init-list has no type: cannot // deduce pair from {"foo", 1} or {"bar", 2} std::unordered_multimap m1 = {std::pair{"foo", 2}, {"bar", 3}}; // guide #2 std::unordered_multimap m2(m1.begin(), m1.end()); // guide #1 } ``` -------------------------------- ### C Initialization Examples Source: https://www.cppreference.com/w/c/language/initialization Demonstrates various initialization techniques for variables, arrays, structs, and pointers in C. Includes static and automatic storage duration initializations, array initializers, struct initializers, and dynamic memory allocation with `malloc` and `free`. Note that VLAs and static pointers with `malloc` cannot be initialized directly. ```c #include int a[2]; // initializes a to {0, 0} int main(void) { int i; // initializes i to an indeterminate value static int j; // initializes j to 0 int k = 1; // initializes k to 1 // initializes int x[3] to 1,3,5 // initializes int* p to &x[0] int x[] = { 1, 3, 5 }, *p = x; // initializes w (an array of two structs) to // { { {1,0,0}, 0}, { {2,0,0}, 0} } struct {int a[3], b;} w[] = {[0].a = {1}, [1].a[0] = 2}; // function call expression can be used for a local variable char* ptr = malloc(10); free(ptr); // Error: objects with static storage duration require constant initializers // static char* ptr = malloc(10); // Error: VLA cannot be initialized // int vla[n] = {0}; } ``` -------------------------------- ### Aggregate Deduction Guides - C++ Source: https://www.cppreference.com/w/cpp/language/ctad Illustrates how class template argument deduction for aggregates typically requires user-defined deduction guides. It shows an example of a deduction guide for a custom aggregate struct and for std::array. ```cpp template struct Agg { A a; B b; }; // implicitly-generated guides are formed from default, copy, and move constructors template Agg(A a, B b) -> Agg; // ^ This deduction guide can be implicitly generated in C++20 Agg agg{1, 2.0}; // deduced to Agg from the user-defined guide template array(T&&... t) -> array, sizeof...(T)>; auto a = array{1, 2, 5u}; // deduced to array from the user-defined guide ``` -------------------------------- ### C Initialization Syntax Examples Source: https://www.cppreference.com/w/c/language/initialization Demonstrates the syntax for explicit initialization of C objects using assignment and brace-enclosed initializer lists. This includes basic assignment, initializer lists, and the new empty initializer syntax introduced in C23. ```c #include int main() { // Explicit initialization with = int x = 5; char arr[] = "hello"; // Explicit initialization with brace-enclosed initializer list int arr2[] = {1, 2, 3, 4, 5}; struct Point { int x; int y; } p = {10, 20}; // Empty initialization (since C23) // int y = {}; // Example usage, requires C23 compiler support // char empty_arr[] = {}; // Example usage, requires C23 compiler support printf("x = %d\n", x); printf("arr = %s\n", arr); printf("arr2[2] = %d\n", arr2[2]); printf("p.x = %d, p.y = %d\n", p.x, p.y); return 0; } ``` -------------------------------- ### Class Template Argument Deduction Example: UniquePtr Source: https://www.cppreference.com/w/cpp/language/deduction_guide Demonstrates Class Template Argument Deduction for a `UniquePtr` template. It shows how deduction guides are generated and used to deduce template arguments during initialization, selecting the appropriate constructor or guide. This example highlights the deduction process for a simple template with a single constructor. ```cpp template struct UniquePtr { UniquePtr(T* t); }; UniquePtr dp{new auto(2.0)}; // One declared constructor: // C1: UniquePtr(T*); // Set of implicitly-generated deduction guides: // F1: template // UniquePtr F(T* p); // F2: template // UniquePtr F(UniquePtr); // copy deduction candidate // imaginary class to initialize: // struct X // { // template // X(T* p); // from F1 // // template // X(UniquePtr); // from F2 // }; // direct-initialization of an X object // with "new double(2.0)" as the initializer // selects the constructor that corresponds to the guide F1 with T = double // For F1 with T=double, the return type is UniquePtr // result: // UniquePtr dp{new auto(2.0)} ``` -------------------------------- ### C++ std::list Deduction Guides Example Source: https://www.cppreference.com/w/cpp/container/list/deduction_guides Demonstrates the use of explicit deduction guides for std::list with iterator ranges from a std::vector. It highlights how list-initialization can affect deduction. ```cpp #include #include int main() { std::vector v = {1, 2, 3, 4}; // uses explicit deduction guide to deduce std::list std::list x(v.begin(), v.end()); // deduces std::list::iterator> // first phase of overload resolution for list-initialization selects the candidate // synthesized from the initializer-list constructor; second phase is not performed // and deduction guide has no effect std::list y{v.begin(), v.end()}; } ``` -------------------------------- ### Create Executable with CMake Source: https://www.cppreference.com/w/User%253ALegalize/CMake This CMakeLists.txt file sets up a minimal CMake project. It specifies the minimum required CMake version, names the project as 'hello_world' and designates it as a C++ project. It then defines an executable target named 'hello_world' to be built from the source file 'hello_world.cpp'. ```cmake cmake_minimum_required(VERSION 2.8.11) project(hello_world CXX) add_executable(hello_world hello_world.cpp) ``` -------------------------------- ### C++ Documentation Template Structure Example Source: https://www.cppreference.com/w/User_talk%253ABregma Illustrates a common templating pattern used in cppreference.com for documenting C++ library components. It shows how a base template can be customized with parameters to generate specific documentation pages, including sidebars and content, promoting maintainability and code reuse across different C++ standard library elements. ```text cpp/numeric/random/uniform_int_distribution ... cpp/numeric/random/uniform_int_distribution/min -> uses Template:cpp/numeric/random/distribution/min via {{cpp/numeric/random/distribution/min|uniform_int_distribution}} ... cpp/numeric/random/uniform_real_distribution ... cpp/numeric/random/uniform_real_distribution/min -> uses Template:cpp/numeric/random/distribution/min via {{cpp/numeric/random/distribution/min|uniform_real_distribution}} ... Template:cpp/numeric/random/distribution/min -> contains the actual content specialized using {{{1}}} Includes e.g. {{cpp/numeric/random/{{{1|}}}/navbar}} which ends up being either Template:cpp/numeric/random/uniform_int_distribution/navbar or Template:cpp/numeric/random/uniform_real_distribution/navbar depending on the parameter Template:cpp/numeric/random/uniform_int_distribution/navbar -> sidebar for uniform_int_distribution Template:cpp/numeric/random/uniform_real_distribution/navbar -> sidebar for uniform_real_distribution ``` -------------------------------- ### C++ strcoll Example Correction (Czech Locale) Source: https://www.cppreference.com/w/Talk%253AMain_Page/suggestions/archive_1 This snippet addresses an incorrect example for std::strcoll in the Czech locale. The original example stated an incorrect ordering of strings. The fix involves updating the examples to use UTF-8 and noting the dependency on installed locale files. ```cpp #include #include #include // ... locale setup code ... // Original incorrect example might have been: // char* s1 = "hrnec"; // char* s2 = "chrt"; // if (std::strcoll(s1, s2) < 0) { /* ... */ } // Corrected example using UTF-8: // Ensure locale is set, e.g., std::setlocale(LC_COLLATE, "cs_CZ.utf8"); char* s1 = "hrnec"; char* s2 = "chrt"; // The actual comparison result depends on the locale's collation rules. ``` -------------------------------- ### C++26 concat_view Deduction Guide Source: https://www.cppreference.com/w/cpp/ranges/concat_view/deduction_guides Provides a deduction guide for `concat_view` in C++26, enabling deduction from ranges. This guide is essential for simplifying the instantiation of `concat_view` when dealing with various range types. The current documentation indicates a lack of illustrative examples. ```cpp template< class... Rs > concat_view( Rs&&... ) -> concat_view...>; ``` -------------------------------- ### C++20 `iota_view::begin()` Example Source: https://www.cppreference.com/w/cpp/ranges/iota_view/begin Demonstrates how to obtain a begin iterator for a `std::views::iota` range and iterate through its elements. This requires the `` and `` headers and C++20 support. ```cpp #include #include int main() { auto iota{std::views::iota(2, 6)}; auto iter{iota.begin()}; while (iter != iota.end()) std::cout << *iter++ << ' '; std::cout << '\n'; } ``` -------------------------------- ### C++ Function Calling Examples Source: https://www.cppreference.com/book/intro/functions Illustrates how to call C++ functions with different parameter types and return void. It shows calling functions that print strings, integers, and a fixed message, demonstrating argument passing and the execution flow. ```cpp #include #include   void print_string(std::string str) { std::cout << str << std::endl; }   void print_ints(int i1, int i2) { std::cout << i1 << ", " << i2 << std::endl; }   void print_hello_world() { std::cout << "Hello World!" << std::endl; }   int main() { print_string("some string"); print_ints(1, 3); print_hello_world(); } ``` -------------------------------- ### C++ Floating-Point Environment Example Source: https://www.cppreference.com/w/cpp/numeric/fenv/FE_DFL_ENV Demonstrates how to interact with the C++ floating-point environment using functions like fetestexcept, fegetround, feraiseexcept, fesetround, and fesetenv. It shows how to check for raised exceptions, get the current rounding mode, raise specific exceptions, change the rounding mode, and restore the default environment. ```cpp #include #include // #pragma STDC FENV_ACCESS ON   void show_env() { const int e = std::fetestexcept(FE_ALL_EXCEPT); if (e & FE_DIVBYZERO) std::cout << "division by zero is raised\n"; if (e & FE_INEXACT) std::cout << "inexact is raised\n"; if (e & FE_INVALID) std::cout << "invalid is raised\n"; if (e & FE_UNDERFLOW) std::cout << "underflow is raised\n"; if (e & FE_OVERFLOW) std::cout << "overflow is raised\n";   switch (std::fegetround()) { case FE_DOWNWARD: std::cout << "rounding down\n"; break; case FE_TONEAREST: std::cout << "rounding to nearest\n"; break; case FE_TOWARDZERO: std::cout << "rounding to zero\n"; break; case FE_UPWARD: std::cout << "rounding up\n"; break; } }   int main() { std::cout << "On startup:\n"; show_env();   std::feraiseexcept(FE_UNDERFLOW | FE_OVERFLOW); std::fesetround(FE_UPWARD);   std::cout << "\nBefore restoration:\n"; show_env();   std::fesetenv(FE_DFL_ENV);   std::cout << "\nAfter reset to default:\n"; show_env(); } ``` -------------------------------- ### std::function Deduction Guide Example (C++) Source: https://www.cppreference.com/w/cpp/utility/functional/function/deduction_guides Demonstrates the usage of std::function deduction guides (specifically guide #1 and #2) for creating std::function objects from a function pointer and a lambda expression. This simplifies type deduction for callable objects. ```cpp #include int func(double) { return 0; } int main() { std::function f{func}; // guide #1 deduces function int i = 5; std::function g = [&](double) { return i; }; // guide #2 deduces function } ``` -------------------------------- ### C++ simd Constructor Example Source: https://www.cppreference.com/w/cpp/experimental/simd/simd/simd Demonstrates constructing std::experimental::simd objects using broadcast, generator, and load constructors with different alignment options. It showcases element-wise addition and printing the results. This example requires the , , and headers. ```cpp #include #include #include namespace stdx = std::experimental; int main() { stdx::native_simd a; // uninitialized a = 1; // all elements set to 1 stdx::native_simd b([](int i) { return i; }); // {0, 1, 2, 3, ...} alignas(stdx::memory_alignment_v>) std::array::size() * 2> mem = {}; for (std::size_t i = 0; i < mem.size(); ++i) mem[i] = i & 1; stdx::native_simd c(&mem[0], stdx::vector_aligned); // {0, 1, 0, 1, ...} stdx::native_simd d(&mem[1], stdx::element_aligned); // {1, 0, 1, 0, ...} auto sum = a + b + c + d; for (std::size_t i = 0; i < sum.size(); ++i) std::cout << sum[i] << ' '; std::cout << '\n'; } ``` -------------------------------- ### C++ Filesystem Status Demonstration Source: https://www.cppreference.com/w/cpp/experimental/fs/directory_entry/status This C++ code snippet demonstrates how to use the library to create various types of files (regular, directory, pipe, socket, symlink) and then determine their status and type using functions like status() and symlink_status(). It includes error handling for non-existent paths and cleans up created files afterward. ```cpp #include #include #include #include #include #include #include #include #include namespace fs = std::experimental::filesystem; void demo_status(const fs::path& p, fs::file_status s) { std::cout << p; // alternative: switch(s.type()) { case fs::file_type::regular: ... } if (fs::is_regular_file(s)) std::cout << " is a regular file\n"; if (fs::is_directory(s)) std::cout << " is a directory\n"; if (fs::is_block_file(s)) std::cout << " is a block device\n"; if (fs::is_character_file(s)) std::cout << " is a character device\n"; if (fs::is_fifo(s)) std::cout << " is a named IPC pipe\n"; if (fs::is_socket(s)) std::cout << " is a named IPC socket\n"; if (fs::is_symlink(s)) std::cout << " is a symlink\n"; if (!fs::exists(s)) std::cout << " does not exist\n"; } int main() { // create files of different kinds fs::create_directory("sandbox"); std::ofstream("sandbox/file"); // create regular file fs::create_directory("sandbox/dir"); mkfifo("sandbox/pipe", 0644); struct sockaddr_un addr; addr.sun_family = AF_UNIX; std::strcpy(addr.sun_path, "sandbox/sock"); int fd = socket(PF_UNIX, SOCK_STREAM, 0); bind(fd, (struct sockaddr*)&addr, sizeof addr); fs::create_symlink("file", "sandbox/symlink"); // demo different status accessors for (auto it = fs::directory_iterator("sandbox"); it != fs::directory_iterator(); ++it) demo_status(*it, it->symlink_status()); // use cached status from directory entry demo_status("dev/null", fs::status("/dev/null")); // direct calls to status demo_status("dev/sda", fs::status("/dev/sda")); demo_status("sandbox/no", fs::status("/sandbox/no")); // cleanup close(fd); fs::remove_all("sandbox"); } ``` -------------------------------- ### C++ Best Viable Function Example - Template Deduction Guide Source: https://www.cppreference.com/w/cpp/language/overload_resolution Shows how template deduction guides influence overload resolution for class templates, particularly when comparing user-defined guides, copy deduction candidates, and non-template constructors. ```cpp template struct A { using value_type = T; A(value_type); // #1 A(const A&); // #2 A(T, T, int); // #3 template A(int, T, U); // #4 }; // #5 is A(A), the copy deduction candidate A x(1, 2, 3); // uses #3, generated from a non-template constructor template A(T) -> A; // #6, less specialized than #5 A a (42); // uses #6 to deduce A and #1 to initialize A b = a; // uses #5 to deduce A and #2 to initialize template A(A) -> A>; // #7, as specialized as #5 A b2 = a; // uses #7 to deduce A> and #1 to initialize ``` -------------------------------- ### Heap Manipulation Example (C++) Source: https://www.cppreference.com/w/cpp/algorithm/make_heap Demonstrates the usage of std::make_heap and std::pop_heap for both max and min heaps. It initializes vectors, creates heaps, extracts the top element, and shows the resulting state of the vectors. This example requires the , , , , and headers. ```cpp #include #include #include #include #include   void print(std::string_view text, const std::vector& v = {}) { std::cout << text << ": "; for (const auto& e : v) std::cout << e << ' '; std::cout << '\n'; }   int main() { print("Max heap");   std::vector v{3, 2, 4, 1, 5, 9}; print("initially, v", v);   std::make_heap(v.begin(), v.end()); print("after make_heap, v", v);   std::pop_heap(v.begin(), v.end()); print("after pop_heap, v", v);   auto top = v.back(); v.pop_back(); print("former top element", {top}); print("after removing the former top element, v", v);   print("\nMin heap");   std::vector v1{3, 2, 4, 1, 5, 9}; print("initially, v1", v1);   std::make_heap(v1.begin(), v1.end(), std::greater<>{}); print("after make_heap, v1", v1);   std::pop_heap(v1.begin(), v1.end(), std::greater<>{}); print("after pop_heap, v1", v1);   auto top1 = v1.back(); v1.pop_back(); print("former top element", {top1}); print("after removing the former top element, v1", v1); } ``` -------------------------------- ### Class Template Argument Deduction: UniquePtr Example Source: https://www.cppreference.com/w/cpp/language/ctad Demonstrates class template argument deduction for a `UniquePtr` template. The compiler generates deduction guides to determine the template argument `T` for `UniquePtr` based on the provided initializer. This example highlights how a constructor `UniquePtr(T* t)` leads to deduction guides that allow `UniquePtr dp{new auto(2.0)};` to deduce `T` as `double`. ```cpp template struct UniquePtr { UniquePtr(T* t); }; UniquePtr dp{new auto(2.0)}; // One declared constructor: // C1: UniquePtr(T*); // Set of implicitly-generated deduction guides: // F1: template // UniquePtr F(T* p); // F2: template // UniquePtr F(UniquePtr); // copy deduction candidate // imaginary class to initialize: // struct X // { // template // X(T* p); // from F1 // // template // X(UniquePtr); // from F2 // }; // direct-initialization of an X object // with "new double(2.0)" as the initializer // selects the constructor that corresponds to the guide F1 with T = double // For F1 with T=double, the return type is UniquePtr // result: // UniquePtr dp{new auto(2.0)} ``` -------------------------------- ### C++ std::basic_regex Deduction Guide Example Source: https://www.cppreference.com/w/cpp/regex/basic_regex/deduction_guides This code snippet demonstrates the usage of the std::basic_regex deduction guide introduced in C++17. It shows how to construct a basic_regex object directly from an iterator range provided by a std::vector. ```cpp #include #include int main() { std::vector v = {'a', 'b', 'c'}; std::basic_regex re(v.begin(), v.end()); // uses explicit deduction guide } ``` -------------------------------- ### Demonstrate time_t Epoch - C Source: https://www.cppreference.com/w/c/chrono/time_t This C code snippet demonstrates the usage of the `time_t` type by showing the start of the epoch. It initializes `time_t` to 0, prints the number of seconds since the epoch began, and then prints the epoch time in a human-readable format using `asctime` and `gmtime`. It requires the ``, ``, and `` headers. ```c #include #include #include int main(void) { time_t epoch = 0; printf("%jd seconds since the epoch began\n", (intmax_t)epoch); printf("%s", asctime(gmtime(&epoch))); } ``` -------------------------------- ### C++11 Variable Initialization Example Source: https://www.cppreference.com/book/Talk%253Aintro/variables Shows the C++11 uniform initialization syntax for declaring and initializing a variable. ```cpp int x = {}; ``` -------------------------------- ### std::pair Deduction Guide Example (C++17) Source: https://www.cppreference.com/w/cpp/utility/pair/deduction_guides This C++ code snippet demonstrates the usage of the explicit deduction guide for std::pair, which was introduced in C++17. This guide helps in deducing the types for a std::pair, especially in cases involving non-copyable types or array-to-pointer conversions. It requires the header. ```cpp #include int main() { int a[2], b[3]; std::pair p{a, b}; // explicit deduction guide is used in this case } ``` -------------------------------- ### Basic std::deque Operations (C++) Source: https://www.cppreference.com/w/cpp/container/deque Demonstrates the creation, insertion (push_front, push_back), and iteration of elements in a std::deque. This example requires the `` and `` headers. ```cpp #include #include   int main() { // Create a deque containing integers std::deque d = {7, 5, 16, 8};   // Add an integer to the beginning and end of the deque d.push_front(13); d.push_back(25);   // Iterate and print values of deque for (int n : d) std::cout << n << ' '; std::cout << '\n'; } ``` -------------------------------- ### C++ Variable Initialization Examples Source: https://www.cppreference.com/book/intro/variables Demonstrates various ways to declare and initialize variables in C++ including fundamental types, strings, and vectors. Shows initialization with values, default construction, and explicit initialization lists. ```cpp int value = {42}; // A variable storing the mass of the Earth (5.97219x10^24 kg) double mass_of_earth = { 5.97219e24 };   // Create a text string with the URL of the site. std::string site_url = {"http://en.cppreference.com/"};   // Create a vector holding the first 5 positive odd numbers. // Note that it doesn’t all have to be on one line, which is handy // if you have a long list. std::vector odd_numbers = { 1, 3, 5, 7, 9 }; int v1 = {}; // initialized to 0 double v2 = {}; // initialized to 0.0 std::string v3 = {}; // initialized to a zero-length string std::vector v4 = {}; // initialized to an empty vector int value{42}; double v{}; std::string s{}; std::vector odd_numbers{ 1, 3, 5, 7, 9 }; int i = 42; // Same as "int i = {42}; double d = 6.28; // Same as "double d = {6.28}; string s = "Hello, world!"; // Same as "string s = {"Hello, world!"}; //int i1{6.28}; // causes an error, because 6.28 is not an integer int i2(6.28); // truncates 6.28 to an integer, so same as "int i2 = {6}";   std::vector v1{3, 5}; // creates a vector with 2 values: {3, 5} std::vector v1(3, 5); // creates a vector with 3 values: {5, 5, 5} ``` -------------------------------- ### C++ std::multimap::size Example Source: https://www.cppreference.com/w/cpp/container/multimap/size Demonstrates how to use the std::multimap::size() function to get the number of elements in a multimap. This example initializes a multimap and asserts that its size is as expected. ```cpp #include #include int main() { std::multimap nums{{1, 'a'}, {1, 'b'}, {2, 'c'}, {2, 'd'}}; assert(nums.size() == 4); } ``` -------------------------------- ### Simple Ruby Code Example without Output Source: https://www.cppreference.com/w/Template_talk%253Aexample A Ruby code example that is expected to produce no direct output, illustrating how documentation templates handle cases where output is not explicitly provided. This is used to discuss superfluous empty paragraphs in example sections. ```ruby puts("Some code, but no output."); ``` -------------------------------- ### std::optional Deduction Guide Example (C++) Source: https://www.cppreference.com/w/cpp/utility/optional/deduction_guides This C++ code snippet demonstrates the explicit deduction guide for std::optional. It shows how std::optional can deduce the correct type, specifically handling array-to-pointer conversion, using `static_assert` to verify the deduced type. ```cpp #include #include   int main() { int a[2]; std::optional oa{a}; // uses explicit deduction guide static_assert(std::is_same_v> == true); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.