From 0cb0c373f62fc9baf593642cade5ad8e0213aacd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciro=20Santilli=20=E5=85=AD=E5=9B=9B=E4=BA=8B=E4=BB=B6=20?= =?UTF-8?q?=E6=B3=95=E8=BD=AE=E5=8A=9F?= Date: Wed, 8 Jan 2020 00:00:00 +0000 Subject: [PATCH] std::set hello world example --- README.adoc | 4 +++- userland/cpp/set.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 userland/cpp/set.cpp diff --git a/README.adoc b/README.adoc index 30cd573..63eb272 100644 --- a/README.adoc +++ b/README.adoc @@ -14068,6 +14068,8 @@ Programs under link:userland/cpp/[] are examples of https://en.wikipedia.org/wik ** link:userland/cpp/temporary_directory.cpp[]: illustrates `std::filesystem::temp_directory_path` and answers https://stackoverflow.com/questions/3379956/how-to-create-a-temporary-directory-in-c/58454949#58454949 * random ** link:userland/cpp/random.cpp[] +* containers +** link:userland/cpp/set.cpp[]: `std::set` contains unique keys [[cpp-multithreading]] ==== C++ multithreading @@ -18701,7 +18703,7 @@ Notably, global monitor operations on memory accesses of regions marked by <>. diff --git a/userland/cpp/set.cpp b/userland/cpp/set.cpp new file mode 100644 index 0000000..f219930 --- /dev/null +++ b/userland/cpp/set.cpp @@ -0,0 +1,39 @@ +// https://cirosantilli.com/linux-kernel-module-cheat#cpp + +#include +#include + +int main() { + std::set s{0, 2}; + + // Insert another element. + auto insert_ret = s.insert(3); + assert(insert_ret.first == s.find(3)); + assert(insert_ret.second == true); + + // Insert something already there, second of return is false. + insert_ret = s.insert(3); + assert(insert_ret.second == false); + + // Check if a value is present. + auto zero = s.find(0); + assert(zero != s.end()); + assert(*zero == 0); + + // Now for a value that is not present. + auto one = s.find(1); + assert(one == s.end()); + +#if __cplusplus > 201703L + // In C++20 we finally have a .contains() to avoid the end mess! + assert(s.contains(0)); + assert(!s.contains(1)); +#endif + + // Remove an element. + // Was present, so return 1; + assert(s.erase(0) == 1); + assert(s.find(0) == s.end()); + // Not present, return 0. + assert(s.erase(0) == 0); +}