Debian Codegraph @

examples/value_modification.cpp

raw
1 #include <frozen/set.h>
2 #include <frozen/string.h>
3 #include <frozen/unordered_map.h>
4 #include <iostream>
5
6 /// MAYBE_CONSTINIT expands to `constinit` if available.
7 #if __cpp_constinit
8 #define MAYBE_CONSTINIT constinit
9 #else
10 #define MAYBE_CONSTINIT
11 #endif
12
13 // To make a frozen::unordered_map where you can modify the values, make a
14 // non-constexpr instance. If available, prefer to use constinit. It will
15 // initialize the map during compilation and detect any exceptions.
16 MAYBE_CONSTINIT static frozen::unordered_map<frozen::string, int, 2> fruits = {
17 {"n_apples", 0},
18 {"n_pears", 0},
19 };
20
21 int main() {
22 // Update the values using at()
23 fruits.at("n_apples") = 10;
24 fruits.at("n_pears") = fruits.at("n_apples") * 2;
25 std::cout << "n_apples: " << fruits.at("n_apples") << std::endl;
26 std::cout << "n_pears: " << fruits.at("n_pears") << std::endl;
27
28 // You can also update values via the iterator returned by find()
29 auto found = fruits.find("n_apples");
30 found->second = 0;
31 std::cout << "n_apples: " << fruits.at("n_apples") << std::endl;
32
33 // Range also works
34 auto range = fruits.equal_range("n_apples");
35 range.first->second = 1337;
36 std::cout << "n_apples: " << fruits.at("n_apples") << std::endl;
37 }