├── Chapter1 ├── Chapter1.vcxproj └── main.cpp ├── Chapter2.1 ├── Chapter2.1.vcxproj └── main.cpp ├── Chapter2.2 ├── Chapter2.2.vcxproj └── main.cpp ├── Chapter3 ├── Chapter3.vcxproj └── main.cpp ├── Chapter4 ├── Chapter4.vcxproj └── main.cpp ├── Chapter5 ├── Chapter5.vcxproj ├── main.cpp ├── playing_cards.cpp └── playing_cards.h ├── Chapter6 ├── Chapter6.vcxproj ├── Race.cpp ├── Race.h └── main.cpp ├── Chapter7 ├── Chapter7.vcxproj ├── Smash.cpp ├── Smash.h ├── dictionary.csv ├── keywords.csv └── main.cpp ├── Chapter8 ├── Chapter8.vcxproj └── main.cpp ├── Chapter9 ├── Chapter9.vcxproj └── main.cpp ├── Code.sln ├── LICENSE └── README.md /Chapter1/Chapter1.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {b6ee4e15-5a1f-4b4f-a52c-667ae934ef7e} 25 | Chapter1 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | stdcpplatest 80 | 81 | 82 | Console 83 | true 84 | 85 | 86 | 87 | 88 | Level3 89 | true 90 | true 91 | true 92 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 93 | true 94 | 95 | 96 | Console 97 | true 98 | true 99 | true 100 | 101 | 102 | 103 | 104 | Level3 105 | true 106 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 107 | true 108 | 109 | 110 | Console 111 | true 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | true 119 | true 120 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 121 | true 122 | 123 | 124 | Console 125 | true 126 | true 127 | true 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /Chapter1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Needs C++14 for std::plus so compile with e.g. 5 | // g++ --std=c++14 hello_world.cpp -o ./hello.out 6 | 7 | template 8 | auto simple_plus(T lhs, U rhs) -> decltype(lhs + rhs) 9 | { 10 | return lhs + rhs; 11 | } 12 | 13 | auto main() -> int { 14 | std::cout << "Hello, world!\n"; 15 | std::plus adder; 16 | std::cout << adder(1, 1.23) << '\n'; // you possibly get a warning because adder is created to add ints 17 | std::cout << std::plus<>{}(1, 1.23) << '\n'; 18 | std::cout << simple_plus(1, 1.23) << '\n'; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Chapter2.1/Chapter2.1.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {273c3030-6833-475f-ab2f-6e8bf90346da} 25 | Chapter1 26 | 10.0 27 | Chapter2.1 28 | 29 | 30 | 31 | Application 32 | true 33 | v143 34 | Unicode 35 | 36 | 37 | Application 38 | false 39 | v143 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | true 46 | v143 47 | Unicode 48 | 49 | 50 | Application 51 | false 52 | v143 53 | true 54 | Unicode 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | true 76 | 77 | 78 | false 79 | 80 | 81 | true 82 | 83 | 84 | false 85 | 86 | 87 | 88 | Level3 89 | true 90 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 91 | true 92 | /std:c++latest %(AdditionalOptions) 93 | 94 | 95 | Console 96 | true 97 | 98 | 99 | 100 | 101 | Level3 102 | true 103 | true 104 | true 105 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | 108 | 109 | Console 110 | true 111 | true 112 | true 113 | 114 | 115 | 116 | 117 | Level3 118 | true 119 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | 122 | 123 | Console 124 | true 125 | 126 | 127 | 128 | 129 | Level3 130 | true 131 | true 132 | true 133 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 134 | true 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /Chapter2.1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void generate_triangle() 5 | { 6 | std::vector data{ 1 }; 7 | for (auto number : data) 8 | { 9 | std::cout << number << ' '; 10 | } 11 | std::cout << '\n'; 12 | } 13 | 14 | int main() 15 | { 16 | generate_triangle(); 17 | } 18 | -------------------------------------------------------------------------------- /Chapter2.2/Chapter2.2.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {740da552-2257-441e-8c77-ef5a9ce71a34} 25 | Chapter12 26 | 10.0 27 | Chapter2.2 28 | 29 | 30 | 31 | Application 32 | true 33 | v143 34 | Unicode 35 | 36 | 37 | Application 38 | false 39 | v143 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | true 46 | v143 47 | Unicode 48 | 49 | 50 | Application 51 | false 52 | v143 53 | true 54 | Unicode 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | true 76 | 77 | 78 | false 79 | 80 | 81 | true 82 | 83 | 84 | false 85 | 86 | 87 | 88 | Level3 89 | true 90 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 91 | true 92 | /std:c++latest %(AdditionalOptions) 93 | 94 | 95 | Console 96 | true 97 | 98 | 99 | 100 | 101 | Level3 102 | true 103 | true 104 | true 105 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | 108 | 109 | Console 110 | true 111 | true 112 | true 113 | 114 | 115 | 116 | 117 | Level3 118 | true 119 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | 122 | 123 | Console 124 | true 125 | 126 | 127 | 128 | 129 | Level3 130 | true 131 | true 132 | true 133 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 134 | true 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /Chapter2.2/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | // In Visual Studio add /std:c++latest to 'properties | C++ | command line | additon options' to get the CTAD, ranges etc 13 | // Or at least C++17 for --std in g++ (CTAD has been around since C++17) 14 | 15 | //Listing 2.2 The next row of Pascal's triangle using the previous row 16 | std::vector get_next_row(const std::vector& last_row) 17 | { 18 | std::vector ret{ 1 }; // CTAD - otherwise say std::vector 19 | if (last_row.empty()) 20 | { 21 | return ret; 22 | } 23 | 24 | for (size_t idx = 0; idx+1 < last_row.size(); ++idx) 25 | { 26 | ret.emplace_back(last_row[idx] + last_row[idx + 1]); 27 | } 28 | ret.emplace_back(1); 29 | return ret; 30 | } 31 | 32 | //Listing 2.3 Generating several rows of Pascal's triangle 33 | auto generate_triangle_first_listing(int rows) 34 | { 35 | std::vector data; 36 | std::vector> triangle; 37 | for (int row = 0; row < rows; ++row) 38 | { 39 | data = get_next_row(data); 40 | triangle.push_back(data); 41 | } 42 | return triangle; 43 | } 44 | 45 | //Listing 2.4 Moving a temporary 46 | auto generate_triangle(int rows) 47 | { 48 | std::vector> triangle{ {1} }; 49 | for (int row = 1; row < rows; ++row) 50 | { 51 | triangle.emplace_back(get_next_row(triangle.back())); 52 | } 53 | return triangle; 54 | } 55 | 56 | //Listing 2.5 Sending the contents to a stream 57 | template 58 | std::ostream& operator << (std::ostream & s, 59 | const std::vector>& triangle) 60 | { 61 | for (const auto& row : triangle) 62 | { 63 | std::ranges::copy(row, std::ostream_iterator(s, " ")); 64 | // If your compile doesn't support ranges, use std::copy instead: 65 | //std::copy(row.begin(), row.end(), std::ostream_iterator(s, " ")); 66 | s << '\n'; 67 | } 68 | return s; 69 | } 70 | 71 | // Listing 2.7 Center justified output 72 | void show_vectors(std::ostream& s, 73 | const std::vector>& v) 74 | { 75 | size_t final_row_size = v.back().size(); 76 | std::string spaces(final_row_size * 3, ' '); 77 | for (const auto& row : v) 78 | { 79 | s << spaces; 80 | if (spaces.size() > 3) 81 | spaces.resize(spaces.size() - 3); 82 | for (const auto& data : row) 83 | { 84 | s << std::format("{: ^{}}", data, 6); 85 | } 86 | s << '\n'; 87 | } 88 | } 89 | // This code is slightly more general than the text of the book, shown above 90 | // since it takes a width of 6, allowing you to try more rows 91 | // Recall, 6 is fine for 16 or so rows. 92 | // Once the entries are more than 4 digits the will overlap 93 | void show_vectors_more_general(std::ostream& s, 94 | const std::vector>& v, size_t width = 6) 95 | { 96 | const auto gaps = width/2; 97 | std::string spaces(v.back().size() * gaps, ' '); 98 | for (const auto& row : v) 99 | { 100 | s << spaces; 101 | if (spaces.size() > gaps) 102 | spaces.resize(spaces.size()- gaps); 103 | for (const auto& data : row) 104 | { 105 | s << std::format("{: ^{}}", data, width); 106 | } 107 | s << '\n'; 108 | } 109 | } 110 | 111 | // Based on 112 | // https://en.cppreference.com/w/cpp/algorithm/ranges/equal 113 | // contexpr not mentioned in the text 114 | constexpr bool is_palindrome(const std::vector& v) 115 | { 116 | auto forward = v | std::views::take(v.size() / 2); 117 | auto backward = v | std::views::reverse | std::views::take(v.size() / 2); 118 | return std::ranges::equal(forward, backward); 119 | } 120 | 121 | // Some tests, using assert 122 | // fails for a 36 row triangle - think about why 123 | void check_properties(const std::vector> & triangle) 124 | { 125 | int expected_total = 1; 126 | size_t row_number = 1; 127 | for (const auto & row : triangle) 128 | { 129 | assert(row.front() == 1); 130 | assert(row.back() == 1); 131 | assert(row.size() == row_number++); 132 | 133 | assert(std::accumulate(row.begin(), 134 | row.end(), 135 | 0) 136 | == expected_total); 137 | 138 | expected_total *= 2; 139 | 140 | // symmetry 141 | assert(is_palindrome(row)); 142 | 143 | auto negative = [](int x) { return x < 0; }; 144 | auto negatives = row | std::views::filter(negative); 145 | assert(negatives.empty()); 146 | } 147 | } 148 | 149 | //Listing 2.16 Show odd numbers as stars 150 | void show_view(std::ostream& s, 151 | const std::vector>& v) 152 | { 153 | const auto gaps = 1; 154 | std::string spaces(v.back().size() * gaps, ' '); 155 | for (const auto& row : v) 156 | { 157 | s << spaces; 158 | if (spaces.size() > gaps) 159 | spaces.resize(spaces.size() - gaps); 160 | auto odds = row | std::views::transform([](int x) { return x % 2 ? '*' : ' '; }); 161 | for (const auto& data : odds) 162 | { 163 | s << data << ' '; 164 | } 165 | s << '\n'; 166 | } 167 | } 168 | 169 | 170 | //Pulls together all the listing gradually added to main through the text 171 | int main() 172 | { 173 | auto triangle = generate_triangle(16); //Change 16 if you want 174 | 175 | // test triangle is correct 176 | check_properties(triangle); 177 | 178 | // display left justified 179 | std::cout << triangle; 180 | 181 | show_vectors(std::cout, triangle); 182 | 183 | // Rather than sticking with a block of 6, we can find out how much we need 184 | // for example if we have more rows 185 | auto biggest = std::max_element(triangle.back().begin(), triangle.back().end()); 186 | auto width = std::to_string(*biggest); 187 | show_vectors_more_general(std::cout, triangle, width.size()+2); 188 | 189 | // Show odd numbers as stars 190 | show_view(std::cout, triangle); 191 | } 192 | 193 | -------------------------------------------------------------------------------- /Chapter3/Chapter3.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {cb04cc30-c39b-4113-8a17-79a38ce001b4} 25 | Chapter21 26 | 10.0 27 | Chapter3.1 28 | 29 | 30 | 31 | Application 32 | true 33 | v143 34 | Unicode 35 | 36 | 37 | Application 38 | false 39 | v143 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | true 46 | v143 47 | Unicode 48 | 49 | 50 | Application 51 | false 52 | v143 53 | true 54 | Unicode 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | true 76 | 77 | 78 | false 79 | 80 | 81 | true 82 | 83 | 84 | false 85 | 86 | 87 | 88 | Level3 89 | true 90 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 91 | true 92 | /std:c++latest %(AdditionalOptions) 93 | 94 | 95 | Console 96 | true 97 | 98 | 99 | 100 | 101 | Level3 102 | true 103 | true 104 | true 105 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | 108 | 109 | Console 110 | true 111 | true 112 | true 113 | 114 | 115 | 116 | 117 | Level3 118 | true 119 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | 122 | 123 | Console 124 | true 125 | 126 | 127 | 128 | 129 | Level3 130 | true 131 | true 132 | true 133 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 134 | true 135 | 136 | 137 | Console 138 | true 139 | true 140 | true 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /Chapter3/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // if you are using fmt instead, swap the last include for the next two lines and change std::format to fmt::format 4 | //#define FMT_HEADER_ONLY 5 | //#include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | 15 | // Listing 3.1 16 | unsigned some_const_number() 17 | { 18 | return 42; 19 | } 20 | 21 | // Listing 3.2 22 | unsigned input() 23 | { 24 | unsigned number; //try a negative number! 25 | while (!(std::cin >> number)) 26 | { 27 | std::cin.clear(); 28 | std::cin.ignore(std::numeric_limits::max(), '\n'); 29 | std::cout << "Please enter a number.\n>"; 30 | } 31 | return number; 32 | } 33 | 34 | //Listing 3.3 35 | void guess_number(unsigned number) 36 | { 37 | std::cout << "Guess the number.\n>"; 38 | unsigned guess = input(); 39 | while (guess != number) 40 | { 41 | std::cout << guess << " is wrong. Try again\n>"; 42 | guess = input(); 43 | } 44 | std::cout << "Well done.\n"; 45 | } 46 | 47 | // Listing 3.4 Taking optional input 48 | // Allow a way to give up 49 | std::optional read_number(std::istream& in) 50 | { 51 | unsigned result{}; 52 | if (in >> result) { 53 | return result; 54 | } 55 | in.clear(); 56 | in.ignore(std::numeric_limits::max(), '\n'); 57 | return {}; 58 | } 59 | 60 | //Listing 3.5 Allow giving up 61 | void guess_number_or_give_up(int number) 62 | { 63 | std::cout << "Guess the number.\n>"; 64 | std::optional guess; 65 | while (guess = read_number(std::cin)) 66 | { 67 | if (guess.value() == number) 68 | { 69 | std::cout << "Well done.\n"; 70 | return; 71 | } 72 | std::cout << guess.value() << " is wrong. Try again\n>"; 73 | } 74 | std::cout << "The number was " << number << "\n"; 75 | } 76 | 77 | 78 | // Listing 3.9 79 | unsigned some_random_number() 80 | { 81 | std::random_device rd; 82 | std::mt19937 mt(rd()); 83 | std::uniform_int_distribution<> dist(0, 100); 84 | return dist(mt); 85 | } 86 | 87 | // Listing 3.11 Function to check if a number is prime 88 | constexpr bool is_prime(int n) 89 | { 90 | //https://en.wikipedia.org/wiki/Primality_test 91 | if (n == 2 || n == 3) 92 | return true; 93 | 94 | if (n <= 1 || n % 2 == 0 || n % 3 == 0) 95 | return false; 96 | 97 | for (int i = 5; i * i <= n; i += 6) 98 | { 99 | if (n % i == 0 || n % (i + 2) == 0) 100 | return false; 101 | } 102 | 103 | return true; 104 | } 105 | 106 | // Listing 3.14, which started as listing 3.13, a function to indicate which digits are correct 107 | // * means correct in the right place 108 | // ^ means correct in the wrong place 109 | // . means wrong 110 | std::string check_which_digits_correct(unsigned number, unsigned guess) 111 | { 112 | auto ns = std::format("{:0>5}", (number)); 113 | auto gs = std::format("{:0>5}", (guess)); 114 | std::string matches(5, '.'); 115 | // which for guesses match... 116 | for (size_t i = 0, stop = gs.length(); i < stop; ++i) 117 | { 118 | char guess_char = gs[i]; 119 | if (i < ns.length() && guess_char == ns[i]) 120 | { 121 | matches[i] = '*'; 122 | ns[i] = '*'; // don't reuse this digit 123 | } 124 | } 125 | // now for guesses that don't match... 126 | for (size_t i = 0, stop = gs.length(); i < stop; ++i) 127 | { 128 | char guess_char = gs[i]; 129 | if (i < ns.length() && matches[i] != '*') 130 | { 131 | if (size_t idx = ns.find(guess_char, 0); 132 | idx != std::string::npos) 133 | { 134 | idx = ns.find(guess_char, idx); 135 | matches[i] = '^'; 136 | ns[idx] = '^'; 137 | } 138 | } 139 | } 140 | return matches; 141 | } 142 | 143 | void check_properties() 144 | { 145 | static_assert(is_prime(2)); 146 | static_assert(is_prime(7321)); 147 | static_assert(is_prime(56897)); 148 | static_assert(is_prime(41521)); 149 | auto got = check_which_digits_correct(12347, 11779); 150 | assert(got == "*.^.."); 151 | got = check_which_digits_correct(12345, 23451); 152 | assert(got == "^^^^^"); 153 | got = check_which_digits_correct(12345, 12345); 154 | assert(got == "*****"); 155 | got = check_which_digits_correct(48533, 12345); 156 | assert(got == "..^^^"); 157 | got = check_which_digits_correct(98041, 41141); 158 | assert(got == "...**"); 159 | assert(is_prime(17231)); 160 | got = check_which_digits_correct(1723, 17231); 161 | assert(got == "^^^^."); 162 | unsigned number = 78737; 163 | got = check_which_digits_correct(number, 87739); 164 | assert(got == "^^**."); 165 | 166 | } 167 | 168 | // Listing 3.15 A much better number guessing game 169 | void guess_number_with_clues(unsigned number, auto message) 170 | { 171 | std::cout << "Guess the number.\n>"; 172 | std::optional guess; 173 | while (guess = read_number(std::cin)) 174 | { 175 | if (guess.value() == number) 176 | { 177 | std::cout << "Well done.\n"; 178 | return; 179 | } 180 | std::cout << message(number, guess.value()); 181 | std::cout << '>'; 182 | } 183 | std::cout << std::format("The number was {}\n", number); 184 | } 185 | 186 | 187 | // Listing 3.12 Generating a prime number 188 | int some_prime_number() 189 | { 190 | std::random_device rd; 191 | std::mt19937 mt{ rd() }; 192 | std::uniform_int_distribution dist{0, 99999}; 193 | int n{}; 194 | while (!is_prime(n)) 195 | { 196 | n = dist(mt); 197 | } 198 | return n; 199 | } 200 | 201 | // Listing 3.19 Using all the clues 202 | void guess_number_with_more_clues(int number, auto messages) 203 | { 204 | std::cout << "Guess the number.\n>"; 205 | std::optional guess; 206 | while (guess = read_number(std::cin)) 207 | { 208 | if (guess.value() == number) 209 | { 210 | std::cout << "Well done."; 211 | return; 212 | } 213 | std::cout << std::format("{:0>5} is wrong. Try again\n", guess.value()); 214 | for (auto message : messages) 215 | { 216 | auto clue = message(guess.value()); 217 | if (clue.length()) 218 | { 219 | std::cout << clue; 220 | break; 221 | } 222 | } 223 | } 224 | std::cout << std::format("The number was {:0>5}\n", (number)); 225 | } 226 | 227 | 228 | int main() 229 | { 230 | check_properties(); 231 | 232 | // guess a number without a clue 233 | guess_number(some_const_number()); 234 | 235 | // alow a non-number to indicate defeat 236 | guess_number_or_give_up(some_const_number()); 237 | 238 | // Listing 3.10 239 | // Guess any number with a clue: 240 | guess_number_with_clues(some_random_number(), [](int number, int guess) { return std::format("Your guess was too {}\n", (guess < number ? "small" : "big")); }); 241 | 242 | // Listing 3.20 243 | // Guess a prime number: 244 | auto check_prime = [](int guess) { 245 | return std::string((is_prime(guess)) ? "" : "Not prime\n"); 246 | }; 247 | 248 | auto check_length = [](int guess) { 249 | return std::string((guess < 100000) ? "" : "Too long\n"); 250 | }; 251 | 252 | const int number = some_prime_number(); 253 | auto check_digits = [number](int guess) { 254 | return std::format("{}\n", 255 | check_which_digits_correct(number, guess)); 256 | }; 257 | std::vector> messages 258 | { 259 | check_length, 260 | check_prime, 261 | check_digits 262 | }; 263 | guess_number_with_more_clues(number, messages); 264 | } 265 | -------------------------------------------------------------------------------- /Chapter4/Chapter4.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {7f372fe2-1c32-42e9-bd2b-d792d14aa41d} 25 | Chapter4 26 | 10.0 27 | Chapter4 28 | 29 | 30 | 31 | Application 32 | true 33 | v143 34 | Unicode 35 | 36 | 37 | Application 38 | false 39 | v143 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | true 46 | v143 47 | Unicode 48 | 49 | 50 | Application 51 | false 52 | v143 53 | true 54 | Unicode 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | Level3 77 | true 78 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 79 | true 80 | /std:c++latest %(AdditionalOptions) 81 | 82 | 83 | Console 84 | true 85 | 86 | 87 | 88 | 89 | Level3 90 | true 91 | true 92 | true 93 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 94 | true 95 | 96 | 97 | Console 98 | true 99 | true 100 | true 101 | 102 | 103 | 104 | 105 | Level3 106 | true 107 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 108 | true 109 | 110 | 111 | Console 112 | true 113 | 114 | 115 | 116 | 117 | Level3 118 | true 119 | true 120 | true 121 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 122 | true 123 | 124 | 125 | Console 126 | true 127 | true 128 | true 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /Chapter4/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // If are using gcc 12 or earlier or clang 15 or earlier you need to clone Howard Hinnant's library for the parse method and use it's date.h 3 | // git clone https://github.com/HowardHinnant/date 4 | // If you get errors with operator<<, you also need to use the date.h from this library 5 | // Also, add 6 | // using date::operator<<; 7 | // just before any 8 | // std::cout << 9 | //#include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | //Listing 4.2 Duration between two time points 17 | void duration_to_end_of_year() 18 | { 19 | std::chrono::time_point now = std::chrono::system_clock::now(); 20 | constexpr auto year = 2022; 21 | auto new_years_eve = std::chrono::year_month_day( 22 | std::chrono::year(year), 23 | std::chrono::month(12), 24 | std::chrono::day(31) 25 | ); 26 | auto event = std::chrono::sys_days(new_years_eve); 27 | std::chrono::duration dur = event - now; 28 | std::cout << dur << " until event\n"; 29 | } 30 | 31 | //Listing 4.4 Use duration to move to a coarser representation 32 | void durations() 33 | { 34 | using namespace std::chrono; 35 | auto nearly_a_day = hours{ 23 }; 36 | days a_day = duration_cast(nearly_a_day); 37 | hours round_trip = a_day; 38 | std::cout << nearly_a_day << " cast to " << a_day 39 | << " and cast back to " << round_trip << '\n'; 40 | } 41 | 42 | //Listing 4.5 Defining a duration 43 | void defining_a_duration() 44 | { 45 | using namespace std::chrono; 46 | using centuries = duration>; 48 | // A type alias, which we used to write like this: 49 | // typedef duration> centuries; 51 | centuries two_hundred_years = centuries(2); 52 | seconds sec = two_hundred_years; 53 | hours hrs = two_hundred_years; 54 | days day_count = duration_cast(two_hundred_years); 55 | std::cout << "Two centuries is approximately " << day_count << '\n'; 56 | } 57 | 58 | //Listing 4.6 Writing and using a concept 59 | // They are called in requirements_and_concepts below, but result in a compliation failure 60 | // Try uncommenting the calls and see what happens 61 | template 62 | concept Quacks = requires(T t) 63 | { 64 | t.Quack(); 65 | }; 66 | 67 | template 68 | void might_be_a_duck(T x) 69 | { 70 | x.Quack(); 71 | } 72 | 73 | template 74 | requires Quacks 75 | void must_be_a_duck(T x) 76 | { 77 | x.Quack(); 78 | } 79 | 80 | void also_must_be_a_duck(Quacks auto x) 81 | { 82 | x.Quack(); 83 | } 84 | 85 | void requirements_and_concepts() 86 | { 87 | //might_be_a_duck(42); // error left of '.Quack' must have class/struct/union 88 | //must_be_a_duck(42); //'must_be_a_duck': no matching overloaded function found, could be 'void must_be_a_duck(T)', the associated constraints are not satisfied 89 | //also_must_be_a_duck(42); 90 | } 91 | 92 | 93 | //Listing 4.7 How many days until the last day of the year? 94 | void countdown() 95 | { 96 | using namespace std::chrono; 97 | time_point now = system_clock::now(); 98 | const auto ymd = year_month_day{ 99 | floor(now) 100 | }; 101 | 102 | auto this_year = ymd.year(); 103 | auto new_years_eve = this_year / December / 31; 104 | 105 | auto event = sys_days(new_years_eve); 106 | duration dur = event - now; 107 | std::cout << duration_cast(dur) 108 | << " until event \n"; 109 | } 110 | 111 | //Listing 4.8 Days until pay day 112 | void pay_day() 113 | { 114 | using namespace std::chrono; 115 | 116 | time_point now = system_clock::now(); 117 | const auto ymd = year_month_day{ 118 | floor(now) 119 | }; 120 | 121 | auto this_year = ymd.year(); 122 | 123 | auto pay_day = ymd.year() / ymd.month() / Friday[last]; 124 | auto event = sys_days(pay_day); 125 | duration dur = event - now; 126 | std::cout << duration_cast(dur) 127 | << " until pay day \n"; 128 | } 129 | 130 | //Listing 4.9 A testable countdown 131 | constexpr 132 | std::chrono::system_clock::duration countdown(std::chrono::system_clock::time_point start) 133 | { 134 | using namespace std::chrono; 135 | 136 | auto days_only = floor(start); 137 | 138 | const auto ymd = year_month_day{ days_only }; 139 | 140 | auto this_year = ymd.year(); 141 | auto new_years_eve = this_year / December / last; 142 | 143 | auto event = sys_days(new_years_eve); 144 | return event - start; 145 | } 146 | 147 | //Listing 4.12 Reading a date 148 | std::optional read_date(std::istream& in) 149 | { 150 | using namespace std::string_literals; 151 | auto format_str = "%Y-%m-%d"s; 152 | std::chrono::year_month_day date; 153 | if (in >> std::chrono::parse(format_str, date)) 154 | { 155 | return date; 156 | } 157 | in.clear(); 158 | std::cout << "Invalid format. Expected " << 159 | format_str << '\n'; 160 | return {}; 161 | } 162 | 163 | //Listing 4.13 Countdown to any event 164 | constexpr std::chrono::system_clock::duration 165 | countdown_to(std::chrono::system_clock::time_point now, 166 | std::chrono::year_month_day date) 167 | { 168 | using namespace std::chrono; 169 | auto event = sys_days(date); 170 | return event - now; 171 | } 172 | 173 | //Listing 4.14 Countdown in local time 174 | std::chrono::system_clock::duration 175 | countdown_in_local_time(std::chrono::system_clock::time_point now, 176 | std::chrono::year_month_day date) 177 | { 178 | using namespace std::chrono; 179 | auto sys_event = zoned_time(current_zone(), local_days{ date }).get_sys_time(); 180 | return sys_event - now; 181 | } 182 | 183 | //Listing 4.10 Check the countdown function 184 | void check_properties() 185 | { 186 | using namespace std::chrono; 187 | constexpr auto new_years_eve = 2022y / December / last; 188 | constexpr auto one_day_away = sys_days{ new_years_eve } - 24h; 189 | constexpr auto result = countdown(one_day_away); 190 | 191 | static_assert(duration_cast(result) == days{ 1 }); 192 | 193 | // An example of another test, not included in the text of the book 194 | auto now = sys_days{ 2022y / March / 27 }; 195 | auto difference = duration_cast(countdown_in_local_time(now, 2022y / March / 28)); 196 | // assert(difference == 23h); // The assert works for the "Europe/London" time zone. Yours might vary 197 | } 198 | 199 | int main() 200 | { 201 | //Listing 4,2 202 | duration_to_end_of_year(); 203 | 204 | //Listing 4.3 205 | durations(); 206 | 207 | //Listing 4.4 208 | defining_a_duration(); 209 | 210 | //Listing 4.5 211 | requirements_and_concepts(); 212 | 213 | //Listing 4.6 214 | countdown(); 215 | 216 | //Listing 4.8 217 | pay_day(); 218 | 219 | //Listing 4.9 220 | std::cout << countdown(std::chrono::system_clock::now()) << " until event \n"; // calling listing 4.7 221 | 222 | //Listing 4.10 223 | check_properties(); 224 | 225 | //Listing 4.11 Call the countdown in a loop 226 | using namespace std::chrono; 227 | for (int i = 0; i < 5; ++i) 228 | { 229 | std::this_thread::sleep_for(5000ms); 230 | auto dur = countdown(system_clock::now()); 231 | std::cout << duration_cast(dur) << 232 | " until event\n"; 233 | } 234 | 235 | //Listing 4.14 A general purpose countdown 236 | std::cout << "Enter a date\n>"; 237 | std::string str; 238 | std::cin >> str; 239 | std::istringstream in(str); 240 | std::optional event_date = read_date(in); 241 | if (event_date) 242 | { 243 | auto dur = countdown_to(system_clock::now(), event_date.value()); 244 | std::cout << duration_cast(dur) << 245 | " until " << event_date.value() << "\n"; 246 | 247 | // Calling the function from listing 4.15 248 | // WARNING - needs the date library compiled. 249 | // See Rainer Grimm's website has instructions for compiling 250 | // and using the library (https://www.modernescpp.com/index.php/calendar-and-time-zone-in-c-20-time-zones) 251 | // Or Howard Hinnant's instructions https://howardhinnant.github.io/date/tz.html#Installation 252 | // You need a curllib and to include the tz.cpp from the src folder in your date clone 253 | // So the build command will be along the line of 254 | // clang++ --std=c++20 main..cpp -o ./main..out 255 | // /dev/date/src/tz.cpp 256 | // -Wall -I/mnt/d/dev/date/include 257 | // -I/dev/date/include 258 | // -lcurl 259 | auto local_dur = countdown_in_local_time(system_clock::now(), event_date.value()); 260 | std::cout << duration_cast(local_dur) << 261 | " until " << event_date.value() << "in local time \n"; 262 | } 263 | 264 | } 265 | -------------------------------------------------------------------------------- /Chapter5/Chapter5.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {d89bf596-102a-45c9-9938-90f3af03a405} 25 | Chapter5 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | /std:c++latest %(AdditionalOptions) 80 | 81 | 82 | Console 83 | true 84 | 85 | 86 | 87 | 88 | Level3 89 | true 90 | true 91 | true 92 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 93 | true 94 | 95 | 96 | Console 97 | true 98 | true 99 | true 100 | 101 | 102 | 103 | 104 | Level3 105 | true 106 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 107 | true 108 | 109 | 110 | Console 111 | true 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | true 119 | true 120 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 121 | true 122 | 123 | 124 | Console 125 | true 126 | true 127 | true 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /Chapter5/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "playing_cards.h" 4 | 5 | #include 6 | #include 7 | void check_properties() 8 | { 9 | using namespace cards; 10 | 11 | try 12 | { 13 | FaceValue value(-1); 14 | assert(false); 15 | } 16 | catch (const std::exception & ) 17 | { 18 | // could assert more here, but it shows an exception was thrown 19 | } 20 | 21 | FaceValue value(1); 22 | assert(value.value() == 1); 23 | 24 | auto cards = create_deck(); 25 | assert(cards.size() == 52); 26 | auto as_set = std::set(cards.begin(), cards.end());//need comparator 27 | assert(as_set.size() == 52); 28 | 29 | assert(is_guess_correct('l', { FaceValue(9), Suit::Clubs }, { FaceValue(6), Suit::Clubs })); 30 | assert(is_guess_correct('h', { FaceValue(5), Suit::Clubs }, { FaceValue(7), Suit::Spades })); 31 | assert(is_guess_correct('h', { FaceValue(3), Suit::Spades }, { FaceValue(5), Suit::Clubs })); 32 | 33 | assert(is_guess_correct('l', 34 | std::variant(Card{ FaceValue(9), Suit::Clubs }), 35 | std::variant(Card{ FaceValue(6), Suit::Clubs }) 36 | ) 37 | ); 38 | assert(is_guess_correct('l', 39 | std::variant(Joker{}), 40 | std::variant(Card{ FaceValue(6), Suit::Clubs }) 41 | ) 42 | ); 43 | assert(is_guess_correct('l', 44 | std::variant(Card{ FaceValue(6), Suit::Clubs }), 45 | std::variant(Joker{}) 46 | ) 47 | ); 48 | assert(is_guess_correct('l', 49 | std::variant(Joker{}), 50 | std::variant(Joker{}) 51 | ) 52 | ); 53 | } 54 | 55 | int main() 56 | { 57 | std::cout << "Some warm up\n"; 58 | cards::CardVersion1 card{ 2, cards::Suit::Clubs }; //after Listing 5.5 59 | std::cout << card << '\n'; 60 | 61 | // This is UB if we don't initialize the fields 62 | cards::Card dangerous_card; 63 | std::cout << dangerous_card <<'\n'; 64 | 65 | std::cout << cards::Card{ cards::FaceValue(1), cards::Suit::Hearts } << '\n'; 66 | 67 | check_properties(); 68 | 69 | std::cout << "Higher/lower game - aces low\n"; 70 | cards::higher_lower(); 71 | 72 | std::cout << "Higher/lower game - aces low, Jokers a free go\n"; 73 | cards::higher_lower_with_jokers(); 74 | } -------------------------------------------------------------------------------- /Chapter5/playing_cards.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "playing_cards.h" 5 | 6 | namespace cards 7 | { 8 | // After Listing 5.29, we noticed the repetition, so said we wcould write a function template instead of having two shuffle functions: 9 | template void shuffle_either_deck(T& deck) 10 | { 11 | std::random_device rd; 12 | std::mt19937 gen{ rd() }; 13 | std::ranges::shuffle(deck, gen); 14 | } 15 | 16 | 17 | // Listing 5.11 Define operator << for a card, improved in Listing 5.12 18 | //std::ostream& operator<<(std::ostream& os, const Card& card) 19 | //{ 20 | // os << card.value << " of " << static_cast(card.suit) << '\n'; 21 | // return os; 22 | //} 23 | 24 | //Listing 5.14 Turn an enum value into a string 25 | std::string to_string(const Suit & suit) 26 | { 27 | using namespace std::literals; 28 | switch (suit) 29 | { 30 | case Suit::Hearts: 31 | return "Hearts"s; 32 | case Suit::Diamonds: 33 | return "Diamonds"s; 34 | case Suit::Clubs: 35 | return "Clubs"s; 36 | case Suit::Spades: 37 | return "Spades"s; 38 | default: 39 | return "?"s; 40 | } 41 | } 42 | 43 | // Not in text, used in main to show first card 44 | std::ostream& operator<<(std::ostream& os, const CardVersion1& card) 45 | { 46 | os << card.value << " of " << static_cast(card.suit); 47 | return os; 48 | } 49 | 50 | // Listing 5.13 Use the enum name rather than value, improved on in listing 5.15 51 | // reanmed stream_insertion_operator here instead of operator<< to avoid name clash 52 | // std::ostream& operator<<(std::ostream& os, const Card& card) 53 | std::ostream& stream_insertion_operator(std::ostream& os, const Card& card) 54 | { 55 | os << card.value().value() << " of " << static_cast(card.suit()); 56 | return os; 57 | } 58 | 59 | //Listing 5.15 Convert card value to a string 60 | std::string to_string(const FaceValue & value) 61 | { 62 | using namespace std::literals; 63 | 64 | switch (value.value()) 65 | { 66 | case 1: 67 | return "Ace"s; 68 | case 11: 69 | return "Jack"s; 70 | case 12: 71 | return "Queen"s; 72 | case 13: 73 | return "King"s; 74 | default: 75 | return std::to_string(value.value()); 76 | } 77 | } 78 | 79 | //Listing 5.16 Show ace, jack, queen, king or number 80 | std::ostream& operator<<(std::ostream& os, const Card& card) 81 | { 82 | os << to_string(card.value()) 83 | << " of " << to_string(card.suit()); 84 | return os; 85 | } 86 | 87 | 88 | // Listing 5.17 Build a deck of cards, given as 89 | // std::array create_deck() in the book 90 | std::array create_deck_first_way() 91 | { 92 | std::array deck; 93 | auto card = deck.begin(); 94 | for (auto suit : 95 | { Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades }) 96 | { 97 | for (int value = 1; value <= 13; value++) 98 | { 99 | *card = Card{ FaceValue(value), suit }; 100 | ++card; 101 | } 102 | } 103 | return deck; 104 | } 105 | 106 | // Listing 5.18 increment our enum 107 | Suit& operator++(Suit& suit) 108 | { 109 | // Dangerous! See https://stackoverflow.com/questions/3475152/why-cant-i-increment-a-variable-of-an-enumerated-type 110 | using IntType = typename std::underlying_type::type; 111 | if (suit == Suit::Spades) 112 | suit = Suit::Hearts; 113 | else 114 | suit = static_cast(static_cast(suit) + 1); 115 | return suit; 116 | } 117 | 118 | //Listing 5.19 Generating the deck of cards 119 | std::array create_deck() 120 | { 121 | std::array deck; 122 | int value = 1; 123 | Suit suit = Suit::Hearts; 124 | std::ranges::generate(deck, [&value, &suit]() { 125 | if (value > 13) 126 | { 127 | value = 1; 128 | ++suit; 129 | } 130 | return Card{ FaceValue(value++), suit }; 131 | }); 132 | return deck; 133 | } 134 | 135 | // Listing 5.22 Shuffle the cards 136 | void shuffle_deck(std::array& deck) 137 | { 138 | std::random_device rd; 139 | std::mt19937 gen{ rd() }; 140 | std::ranges::shuffle(deck, gen); 141 | } 142 | 143 | // Listing 5.23 Is the guess correct? 144 | bool is_guess_correct(char guess, const Card & current, const Card & next) 145 | { 146 | return (guess == 'h' && next > current) 147 | || (guess == 'l' && next < current); 148 | } 149 | 150 | //Listing 5.24 Higher lower game 151 | void higher_lower() 152 | { 153 | auto deck = create_deck(); 154 | shuffle_deck(deck); 155 | 156 | size_t index = 0; 157 | while (index + 1 < deck.size()) 158 | { 159 | std::cout << deck[index] 160 | << ": Next card higher (h) or lower (l)?\n>"; 161 | char c; 162 | std::cin >> c; 163 | bool ok = is_guess_correct(c, deck[index], deck[index + 1]); 164 | if (!ok) 165 | { 166 | std::cout << "Next card was " << deck[index + 1] << '\n'; 167 | break; 168 | } 169 | ++index; 170 | } 171 | std::cout << "You got " << index << " correct\n"; 172 | } 173 | 174 | //Listing 5.28 Create an extended deck 175 | std::array, 54> create_extended_deck() 176 | { 177 | std::array, 54> deck{ Joker{} , Joker{} }; 178 | std::array cards = create_deck(); 179 | std::ranges::copy(cards, deck.begin() + 2); 180 | return deck; 181 | } 182 | 183 | //Listing 5.28 Shuffle an extended deck 184 | void shuffle_deck(std::array, 54>& deck) 185 | { 186 | std::random_device rd; 187 | std::mt19937 gen{ rd() }; 188 | std::ranges::shuffle(deck, gen); 189 | } 190 | 191 | //Listing 5.30 Is the guess correct for an extended deck 192 | bool is_guess_correct(char c, 193 | const std::variant& current, 194 | const std::variant& next) 195 | { 196 | if (std::holds_alternative(current) || std::holds_alternative(next)) 197 | return true; 198 | Card current_card = std::get(current); 199 | Card next_card = std::get(next); 200 | return is_guess_correct(c, current_card, next_card); 201 | } 202 | 203 | //Listing 5.31 Stream out cards and jokers 204 | std::ostream& operator<<(std::ostream& os, const std::variant& card) 205 | { 206 | if (std::holds_alternative(card)) 207 | os << "JOKER"; 208 | else 209 | os << std::get(card); 210 | return os; 211 | } 212 | 213 | //Listing 5.32 Higher lower game with Jokers too 214 | void higher_lower_with_jokers() 215 | { 216 | auto deck = create_extended_deck(); 217 | shuffle_deck(deck); 218 | 219 | size_t index = 0; 220 | while (index + 1 < deck.size()) 221 | { 222 | std::cout << deck[index] 223 | << ": Next card higher (h) or lower (l)?\n>"; 224 | char c; 225 | std::cin >> c; 226 | bool ok = is_guess_correct(c, deck[index], deck[index + 1]); 227 | if (!ok) 228 | { 229 | std::cout << "Next card was " << deck[index + 1] << '\n'; 230 | break; 231 | } 232 | ++index; 233 | } 234 | std::cout << "You got " << index << " correct\n"; 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /Chapter5/playing_cards.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | namespace cards 11 | { 12 | //Listing 5.4 13 | enum class Suit { 14 | Hearts, 15 | Diamonds, 16 | Clubs, 17 | Spades 18 | }; 19 | 20 | //Listing 5.5 and 5.8, just called Card in the text 21 | struct CardVersion1 22 | { 23 | int value{}; 24 | Suit suit{}; 25 | }; 26 | 27 | std::ostream& operator<<(std::ostream& os, const CardVersion1& card); 28 | 29 | //Listing 5.7 A type for a face value 30 | class FaceValue 31 | { 32 | public: 33 | explicit FaceValue(int value) : value_(value) 34 | { 35 | if (value_ < 1 || value_ > 13) 36 | { 37 | throw std::invalid_argument("Face value invalid"); 38 | } 39 | } 40 | int value() const 41 | { 42 | return value_; 43 | } 44 | auto operator<=>(const FaceValue&) const = default;//Added in Listing 5.21 to provide less than 45 | private: 46 | int value_; 47 | }; 48 | 49 | //Listing 5.10 A card class 50 | class Card 51 | { 52 | public: 53 | Card() = default; 54 | Card(FaceValue value, Suit suit) : 55 | value_(value), 56 | suit_(suit) 57 | { 58 | } 59 | FaceValue value() const { return value_; } 60 | Suit suit() const { return suit_; } 61 | 62 | //Less than considered in listing, 5.20 63 | //bool operator<(const Card&) const 64 | //{ 65 | // return value < other.value&& suit < other.suit; 66 | //} 67 | 68 | // Added in Listing 5.21 to provide less than, and more besides 69 | auto operator<=>(const Card&) const = default;//means aces low 70 | private: 71 | FaceValue value_{1}; 72 | Suit suit_{}; 73 | }; 74 | 75 | 76 | std::ostream& operator<<(std::ostream& os, const Card& card); // Listing 5.10 77 | 78 | // various other functions, defined in the source file and declared here 79 | Suit& operator++(Suit& suit); 80 | std::string to_string(const Suit & suit); 81 | std::string to_string(const FaceValue & value); 82 | 83 | std::array create_deck(); 84 | void shuffle_deck(std::array& deck); 85 | 86 | bool is_guess_correct(char guess, const Card& current, const Card& next); 87 | void higher_lower(); 88 | 89 | //Listing 5.26 A joker 90 | struct Joker 91 | { 92 | }; 93 | 94 | std::array, 54> create_extended_deck(); 95 | void shuffle_deck(std::array, 54>& deck); 96 | bool is_guess_correct(char c, 97 | const std::variant& current, 98 | const std::variant& next); 99 | std::ostream& operator<<(std::ostream& os, const std::variant& card); 100 | void higher_lower_with_jokers(); 101 | } 102 | -------------------------------------------------------------------------------- /Chapter6/Chapter6.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {2707b232-4d22-487e-80eb-4e5bd325aa2a} 25 | Chapter61 26 | 10.0 27 | Chapter6 28 | 29 | 30 | 31 | Application 32 | true 33 | v143 34 | Unicode 35 | 36 | 37 | Application 38 | false 39 | v143 40 | true 41 | Unicode 42 | 43 | 44 | Application 45 | true 46 | v143 47 | Unicode 48 | 49 | 50 | Application 51 | false 52 | v143 53 | true 54 | Unicode 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | Level3 77 | true 78 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 79 | true 80 | /std:c++latest %(AdditionalOptions) 81 | 82 | 83 | Console 84 | true 85 | 86 | 87 | 88 | 89 | Level3 90 | true 91 | true 92 | true 93 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 94 | true 95 | 96 | 97 | Console 98 | true 99 | true 100 | true 101 | 102 | 103 | 104 | 105 | Level3 106 | true 107 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 108 | true 109 | 110 | 111 | Console 112 | true 113 | 114 | 115 | 116 | 117 | Level3 118 | true 119 | true 120 | true 121 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 122 | true 123 | 124 | 125 | Console 126 | true 127 | true 128 | true 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /Chapter6/Race.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "Race.h" 6 | 7 | // Listing 6.5 Draw each blob's current position 8 | void Race::draw_blobs(const std::vector& blobs) 9 | { 10 | const int bag_height = 3; 11 | const int race_height = 8; 12 | for (int y = race_height; y >= 0; --y) 13 | { 14 | std::string output = y >= bag_height ? " " : "| "; 15 | for (const auto& blob : blobs) 16 | { 17 | if (blob.total_steps() >= y) 18 | { 19 | output += "* "; 20 | } 21 | else 22 | { 23 | output += " "; 24 | } 25 | } 26 | output += y >= bag_height ? ' ' : '|'; 27 | std::cout << output << '\n'; 28 | } 29 | const int edges = 3; 30 | std::cout << std::string(blobs.size() * 2 + edges, '-') << '\n'; 31 | } 32 | 33 | // Listing 6.7 Move all the blobs 34 | void Race::move_blobs(std::vector& blobs) 35 | { 36 | for (auto& blob : blobs) 37 | { 38 | blob.step(); 39 | } 40 | } 41 | 42 | // Listing 6.8 A somewhat predictable race 43 | void Race::race(std::vector& blobs) 44 | { 45 | using namespace std::chrono; 46 | const int max = 3; 47 | std::cout << "\x1B[2J\x1B[H"; 48 | for (int i = 0; i < max; ++i) 49 | { 50 | draw_blobs(blobs); 51 | move_blobs(blobs); 52 | std::this_thread::sleep_for(1000ms); 53 | std::cout << "\x1B[2J\x1B[H"; 54 | } 55 | draw_blobs(blobs); 56 | } 57 | 58 | // Listing 6.15 A less predictable race 59 | void Race::race(std::vector>& blobs) 60 | { 61 | using namespace std::chrono; 62 | const int max = 3; 63 | std::cout << "\x1B[2J\x1B[H"; 64 | for (int i = 0; i < max; ++i) 65 | { 66 | draw_blobs(blobs); 67 | move_blobs(blobs); 68 | std::this_thread::sleep_for(1000ms); 69 | std::cout << "\x1B[2J\x1B[H"; 70 | } 71 | draw_blobs(blobs); 72 | } 73 | 74 | // Listing 6.16 Move all the blobs 75 | void Race::move_blobs(std::vector>& blobs) 76 | { 77 | for (auto& blob : blobs) 78 | { 79 | blob->step(); 80 | } 81 | } 82 | 83 | // Listing 6.17 Draw each blob's current position 84 | void Race::draw_blobs(const std::vector>& blobs) 85 | { 86 | const int bag_height = 3; 87 | for (int y = 8; y >= 0; --y) 88 | { 89 | std::string output = y > 2 ? " " : "| "; 90 | for (const auto& blob : blobs) 91 | { 92 | if (blob->total_steps() >= y) 93 | output += "* "; 94 | else 95 | output += " "; 96 | } 97 | output += y >= bag_height ? ' ' : '|'; 98 | std::cout << output << '\n'; 99 | } 100 | std::cout << std::string(blobs.size() * 2 + 3, '-') << '\n'; 101 | } 102 | -------------------------------------------------------------------------------- /Chapter6/Race.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | namespace Race 8 | { 9 | // Listing 6.2 A base class 10 | class Blob 11 | { 12 | public: 13 | virtual ~Blob() = default; 14 | 15 | Blob() = default; 16 | Blob(Blob const&) = delete; 17 | Blob& operator=(Blob const&) = delete; 18 | 19 | virtual void step() = 0; 20 | virtual int total_steps() const = 0; 21 | }; 22 | 23 | // Listing 6.3 A Blob taking constant sized steps 24 | // we noted in further considerations we could mark this as final 25 | class StepperBlob final : public Blob 26 | { 27 | int y = 0; 28 | public: 29 | void step() override 30 | { 31 | y += 2; 32 | } 33 | int total_steps() const override 34 | { 35 | return y; 36 | } 37 | }; 38 | 39 | // Listing 6.11 A general purpose random blob 40 | // We started with temmplate-head 41 | // template 42 | // then consdiered using the concept std::invocable<> 43 | // for the generator in the text 44 | template T, typename U> 45 | class RandomBlob : public Blob 46 | { 47 | int y = 0; 48 | T generator; 49 | U distribution; 50 | public: 51 | RandomBlob(T gen, U dis) 52 | : generator(gen), distribution(dis) 53 | { 54 | 55 | } 56 | void step() override 57 | { 58 | y += static_cast(distribution(generator)); 59 | } 60 | int total_steps() const override { return y; } 61 | }; 62 | 63 | void move_blobs(std::vector& blobs); 64 | void draw_blobs(const std::vector& blobs); 65 | void race(std::vector& blobs); 66 | 67 | void race(std::vector>& blob); 68 | void move_blobs(std::vector>& blobs); 69 | void draw_blobs(const std::vector>& blob); 70 | } -------------------------------------------------------------------------------- /Chapter6/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "Race.h" 9 | 10 | void check_properties() 11 | { 12 | // Listing 6.4 Check steps move a blob forward 13 | Race::StepperBlob blob; 14 | blob.step(); 15 | assert(blob.total_steps() == 2); 16 | 17 | // Listing 6.10 Type traits to check for special member functions 18 | static_assert(!std::is_constructible::value); // 0 for ABC 19 | // alternatively use _v instead of ::value 20 | static_assert(!std::is_constructible_v); // 0 for ABC 21 | // or is_default_constructible_v 22 | static_assert(!std::is_default_constructible_v); // 0 for ABC 23 | static_assert( std::is_destructible_v); 24 | static_assert(!std::is_copy_constructible_v); 25 | static_assert(!std::is_copy_assignable_v); 26 | static_assert(!std::is_move_constructible_v); 27 | static_assert(!std::is_move_assignable_v); 28 | static_assert( std::has_virtual_destructor_v); 29 | 30 | std::random_device rd; 31 | Race::RandomBlob rnd_blob{ 32 | std::default_random_engine{ rd() }, 33 | std::uniform_int_distribution{ 0, 4 } 34 | }; 35 | rnd_blob.step(); 36 | assert(rnd_blob.total_steps() >= 0); 37 | 38 | Race::RandomBlob another_rnd_blob{ 39 | std::default_random_engine{ rd() }, 40 | std::poisson_distribution{ 2 } 41 | }; 42 | another_rnd_blob.step(); 43 | assert(another_rnd_blob.total_steps() >= 0); 44 | 45 | // Listing 6.12 Testing with random generators and distributions 46 | Race::RandomBlob random_blob([]() { return 0; }, [](auto gen) { return gen(); }); 47 | random_blob.step(); 48 | assert(random_blob.total_steps() == 0); 49 | } 50 | 51 | // Listing 6.8 A warm up race 52 | void race_steppers() 53 | { 54 | std::vector blobs(4); 55 | std::random_device rd; 56 | const int max = 3; 57 | for (int i = 0; i < max; ++i) 58 | { 59 | Race::draw_blobs(blobs); 60 | Race::move_blobs(blobs); 61 | } 62 | } 63 | 64 | // Listing 6.18 Create blobs for a proper race 65 | std::vector> create_blobs(int number) 66 | { 67 | using namespace Race; 68 | std::vector> blobs; 69 | std::random_device rd; 70 | for (int i = 0; i < number/2; ++i) 71 | { 72 | blobs.emplace_back(std::make_unique()); 73 | blobs.emplace_back(std::make_unique>> 75 | ( 76 | std::default_random_engine{ rd() }, 77 | std::uniform_int_distribution{ 0, 4 } 78 | ) 79 | ); 80 | } 81 | return blobs; 82 | } 83 | 84 | int main() 85 | { 86 | check_properties(); 87 | 88 | // Running both races together might be confusing, so 89 | // choose a type of race; either 6.9 (just steppers) or 6.18 (various types) 90 | 91 | // Listing 6.9 A warm up race 92 | // // Uncomment and comment out 2nd race, if you want 93 | //std::vector blobs(4); 94 | //Race::race(blobs); 95 | 96 | // Listing 6.19 A proper race 97 | auto blobs = create_blobs(8); 98 | Race::race(blobs); 99 | } 100 | -------------------------------------------------------------------------------- /Chapter7/Chapter7.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {a37213e0-cc6c-40d3-b66c-6fa879df9508} 25 | Chapter7 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | /std:c++latest %(AdditionalOptions) 80 | 81 | 82 | Console 83 | true 84 | 85 | 86 | 87 | 88 | Level3 89 | true 90 | true 91 | true 92 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 93 | true 94 | 95 | 96 | Console 97 | true 98 | true 99 | true 100 | 101 | 102 | 103 | 104 | Level3 105 | true 106 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 107 | true 108 | 109 | 110 | Console 111 | true 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | true 119 | true 120 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 121 | true 122 | 123 | 124 | Console 125 | true 126 | true 127 | true 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /Chapter7/Smash.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "Smash.h" 7 | 8 | // Listing 7.9 Transform a string to lower case 9 | // Based on https://en.cppreference.com/w/cpp/string/byte/tolower 10 | std::string str_tolower(std::string s) { 11 | std::transform(s.begin(), s.end(), s.begin(), 12 | [](unsigned char c) { return std::tolower(c); } 13 | ); 14 | return s; 15 | } 16 | 17 | // Listing 7.10 Load a file into a multimap 18 | std::multimap smashing::load_dictionary(const std::string& filename) 19 | { 20 | std::multimap dictionary; 21 | std::ifstream infile{ filename }; 22 | if (infile) 23 | { 24 | std::string line; 25 | while (std::getline(infile, line)) 26 | { 27 | size_t position = line.find(','); 28 | if (position != std::string::npos) 29 | { 30 | std::string key{ line.substr(0, position) }; 31 | std::string value{ line.substr(position + 1) }; 32 | key = str_tolower(key); 33 | //dictionary.insert({ key, value }); or 34 | dictionary.emplace(key, value); 35 | } 36 | else 37 | { 38 | std::cout << "***Invalid line\n" << line << "\nin " << filename << "***\n\n"; 39 | } 40 | } 41 | } 42 | else 43 | { 44 | // report error - TODO could throw instead 45 | std::cout << "Failed to open " << filename << '\n'; 46 | } 47 | return dictionary; 48 | } 49 | 50 | // Listing 7.8 Find an overlapping word more efficiently 51 | std::pair smashing::find_overlapping_word(std::string word, 52 | const std::map& dictionary) 53 | { 54 | size_t offset = 1; 55 | while (offset < word.size()) 56 | { 57 | auto stem = word.substr(offset); 58 | auto [lb, ub] = dictionary.equal_range(stem); 59 | if (lb != dictionary.end() && 60 | stem == lb->first.substr(0, stem.size())) 61 | { 62 | return { lb->first, offset }; 63 | } 64 | ++offset; 65 | } 66 | return { "", -1 }; 67 | } 68 | 69 | // Could use 70 | //#include 71 | //#include 72 | 73 | // Listing 7.6 Simple answer smash game 74 | void smashing::simple_answer_smash( 75 | const std::map& keywords, 76 | const std::map& dictionary) 77 | { 78 | for (const auto& [word, definition] : keywords) 79 | { 80 | auto [second_word, offset] = find_overlapping_word(word, dictionary); 81 | if (offset == -1) 82 | { 83 | std::cout << "Not match for " << word << '\n'; 84 | continue; 85 | } 86 | std::string second_definition = dictionary.at(second_word); 87 | std::cout << definition << "\nAND\n" << second_definition << '\n'; 88 | 89 | std::string answer = word.substr(0, offset) + second_word; 90 | // Or more efficiently, 91 | //std::string answer = std::format("{}{}", std::string_view(word).substr(0, offset), second_word); 92 | 93 | std::string response; 94 | std::getline(std::cin, response); 95 | if (response == answer) 96 | { 97 | std::cout << "CORRECT!!!!!!!!!\n"; 98 | } 99 | else 100 | { 101 | std::cout << answer << '\n'; 102 | } 103 | std::cout << word << ' ' << second_word << "\n\n\n"; 104 | } 105 | } 106 | 107 | // Listing 7.14 Better answer smash game 108 | void smashing::answer_smash( 109 | const std::multimap& keywords, 110 | const std::multimap& dictionary) 111 | { 112 | std::mt19937 gen{ std::random_device{}() }; 113 | auto select_one = [&gen](auto lb, auto ub, auto dest) { 114 | std::sample(lb, ub, dest, 1, gen); 115 | }; 116 | const int count = 5; 117 | std::vector> first_words; 118 | std::ranges::sample(keywords, std::back_inserter(first_words), count, gen); 119 | for (const auto& [word, definition] : first_words) 120 | { 121 | auto [second_word, second_definition, offset] = select_overlapping_word_from_dictionary(word, dictionary, select_one); 122 | if (second_word == "") 123 | { 124 | continue; 125 | } 126 | std::cout << definition << "\nAND\n" << second_definition << '\n'; 127 | std::string answer = word.substr(0, offset) + second_word; 128 | std::string response; 129 | std::getline(std::cin, response); 130 | if (str_tolower(response) == answer) 131 | { 132 | std::cout << "CORRECT!!!!!!!!!\n"; 133 | } 134 | else 135 | { 136 | std::cout << answer << '\n'; 137 | } 138 | std::cout << word << ' ' << second_word << "\n\n\n"; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /Chapter7/Smash.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | namespace smashing 8 | { 9 | // Listing 7.11 Select a word from a multimap 10 | template 11 | std::tuple select_overlapping_word_from_dictionary(std::string word, 12 | const std::multimap& dictionary, 13 | T select_function) 14 | { 15 | size_t offset = 1; 16 | while (offset < word.size()) 17 | { 18 | auto stem = word.substr(offset); 19 | auto lb = dictionary.lower_bound(stem); 20 | auto beyond_stem = stem; 21 | beyond_stem += ('z' + 1); 22 | auto ub = dictionary.upper_bound(beyond_stem); 23 | if (lb != dictionary.end() && 24 | lb != ub) 25 | { 26 | std::vector> dest; 27 | select_function(lb, ub, std::back_inserter(dest)); 28 | auto found = dest[0].first; 29 | auto definition = dest[0].second; 30 | return { found, definition, offset }; 31 | } 32 | ++offset; 33 | } 34 | return { "", "", -1 }; 35 | } 36 | 37 | std::pair find_overlapping_word(std::string word, 38 | const std::map& dictionary); 39 | void simple_answer_smash( 40 | const std::map& keywords, 41 | const std::map& dictionary); 42 | 43 | std::multimap load_dictionary(const std::string& filename); 44 | void answer_smash( 45 | const std::multimap& keywords, 46 | const std::multimap& dictionary); 47 | } 48 | -------------------------------------------------------------------------------- /Chapter7/keywords.csv: -------------------------------------------------------------------------------- 1 | and,alternative operators: as an alternative for && (Logical AND operator) 2 | and_eq,alternative operators: as an alternative for &= 3 | asm,Declaration of an inline assembly block 4 | auto,auto placeholder type specifier 5 | bitand,alternative operators: as an alternative for & 6 | bitor,alternative operators: as an alternative for | 7 | bool,type, capable of holding one of the two values: true or false. 8 | break,Causes the enclosing for, range-for, while or do-while loop or switch statement to terminate. 9 | char,type for character representation which can be most efficiently processed on the target system 10 | class,user defined type with private members by default 11 | compl,alternative operators: as an alternative for ~ 12 | concept,declares a named type requirement 13 | const,defines that the type is constant. 14 | consteval,specifies that a function is an immediate function, that is, every call to the function must produce a compile-time constant 15 | constexpr,specifies that the value of a variable or function can appear in constant expressions 16 | constinit,asserts that a variable has static initialization, i.e. zero initialization and constant initialization, otherwise the program is ill-formed 17 | const_cast,Converts between types with different cv-qualification. 18 | continue,Causes the remaining portion of the enclosing for, range-for, while or do-while loop body to be skipped. 19 | co_await,suspends a coroutine and returns control to the caller. 20 | co_return,return statement in a coroutine 21 | co_yield,yields a value from a coroutine 22 | default,as the declaration of the catch all case label in a switch statement; as an explicit instruction to the compiler to generate special member function or a comparison operator for a class. 23 | delete,Destroys object(s) previously allocated by the new expression and releases obtained memory area 24 | double,floating point type matching IEEE-754 binary64 format if supported. 25 | dynamic_cast,Safely converts pointers and references to classes up, down, and sideways along the inheritance hierarchy. 26 | else,if statement, as the declaration of the alternative branch 27 | enum,a distinct type whose value is restricted to a range of values, which may include several explicitly named constants 28 | explicit,Specifies that a constructor or conversion function or deduction guide is explicit, that is, it cannot be used for implicit conversions and copy-initialization. 29 | export,Marks a declaration, a group of declarations, or another module as exported by the current module. 30 | extern,language linkage specification 31 | false,boolean literal, not true 32 | float,single precision floating-point type matching IEEE-754 binary32 format if supported. 33 | for,Executes init-statement once, then executes statement and iteration-expression repeatedly, until the value of condition becomes false. The test takes place before each iteration. 34 | friend,declaration appears in a class body and grants a function or another class access to private and protected members of the class 35 | goto,considered harmful 36 | if,Conditionally executes another statement. 37 | int,basic integer type 38 | long,Modifies the basic integer type; target type will have width of at least 32 bits. 39 | mutable,permits modification of the specified class member even if the containing object is declared const. 40 | namespace,provide a method for preventing name conflicts in large projects 41 | new,Creates and initializes objects with dynamic storage duration, that is, objects whose lifetime is not necessarily limited by the scope in which they were created. 42 | noexcept,Specifies whether a function could throw exceptions. 43 | not,alternative operators: as an alternative for ! 44 | not_eq,alternative operators: as an alternative for != 45 | or,alternative operators: as an alternative for || 46 | or_eq,alternative operators: as an alternative for |= 47 | reinterpret_cast,Converts between types by reinterpreting the underlying bit pattern. 48 | requires,specifies an associated constraint in template deduction 49 | return,Terminates the current function and returns the specified value (if any) to the caller. 50 | short,interger type optimized for space and will have width of at least 16 bits. 51 | sizeof,Queries size of the object or type. 52 | static,declarations of class members not bound to specific instances 53 | static_assert,Performs compile-time assertion checking. 54 | static_cast,Converts between types using a combination of implicit and user-defined conversions. 55 | struct,user defined type with public members by default 56 | switch,Transfers control to one of several statements, depending on the value of a condition. 57 | template,a family of classes or functions parameterized by one or more parameters 58 | this,is a prvalue expression whose value is the address of the implicit object parameter 59 | thread_local,thread storage duration 60 | true,boolean literal, not false 61 | typedef,creates an alias that can be used anywhere in place of a (possibly complex) type name. 62 | typeid,Queries information of a type. Used where the dynamic type of a polymorphic object must be known and for static type identification. 63 | typename,In the template parameter list of a template declaration, can be used as an alternative to class to declare type template parameters and template template parameters 64 | union,a special class type that can hold only one of its non-static data members at a time. 65 | using,Introduces a name that is defined elsewhere into the declarative region where this declaration appears. 66 | virtual,specifies that a non-static member function is supports dynamic dispatch 67 | void,parameter list of a function with no parameters 68 | while,used to control the flow of execution. First, it checks the condition, if condition matches, statements the following while will be executed. 69 | xor,alternative operators: as an alternative for ^ 70 | xor_eq,alternative operators: as an alternative for ^= 71 | -------------------------------------------------------------------------------- /Chapter7/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "Smash.h" 8 | 9 | 10 | // Listing 7.5 Find an overlapping word 11 | std::pair find_overlapping_word_v1(std::string word, 12 | const std::map& dictionary) 13 | { 14 | size_t offset = 1; 15 | while (offset < word.size()) 16 | { 17 | auto stem = word.substr(offset); 18 | for (const auto & [k, v] : dictionary) 19 | { 20 | auto key_stem = k.substr(0, stem.size()); // v1, for v2 use lower bound 21 | if (key_stem == stem) 22 | { 23 | return std::make_pair(k, offset); 24 | } 25 | } 26 | ++offset; 27 | } 28 | return std::make_pair("", -1); 29 | } 30 | 31 | // Listing 7.13 Test properties 32 | void check_properties() 33 | { 34 | using namespace smashing; 35 | std::map first{ 36 | { "sprint", ""}, 37 | { "swim", ""}, 38 | { "torch", ""}, 39 | { "assault", ""} 40 | }; 41 | std::map second{ 42 | { "integer", ""}, 43 | { "immuatble", ""}, 44 | { "class", ""}, 45 | { "struct", ""}, 46 | { "vector", ""}, 47 | }; 48 | 49 | auto [got1, offset1] = find_overlapping_word("sprint", second); 50 | assert(got1 == "integer"); 51 | auto [got2, offset2] = find_overlapping_word("minus", second); 52 | assert(got2 == "struct"); 53 | auto [got3, offset3] = find_overlapping_word("vector", first); 54 | assert(got3 == "torch"); 55 | 56 | auto [got4, offset4] = find_overlapping_word("class", first); 57 | assert(got4 == "assault"); 58 | assert(offset4 == 2); 59 | 60 | auto [got, offset] = find_overlapping_word("class", {}); 61 | assert(got == ""); 62 | assert(offset == -1); 63 | 64 | std::multimap first_2{ 65 | { "sprint", ""}, 66 | { "swim", ""}, 67 | { "torch", ""}, 68 | { "assault", ""} 69 | }; 70 | std::multimap second_2{ 71 | { "integer", ""}, 72 | { "immuatble", ""}, 73 | { "class", ""}, 74 | { "struct", ""}, 75 | { "vector", ""}, 76 | }; 77 | 78 | // Listing 7.12 A fake generator for testing 79 | auto select_first = [](auto lb, auto ub, auto dest) { 80 | *dest = *lb; 81 | }; 82 | auto [word1, definition1, offset1_2] = select_overlapping_word_from_dictionary("sprint", second_2, select_first); 83 | assert(word1 == "integer"); 84 | auto [word2, definition2, offset2_2] = select_overlapping_word_from_dictionary("minus", second_2, select_first); 85 | assert(word2 == "struct"); 86 | auto [word3, definition3, offset3_2] = select_overlapping_word_from_dictionary("vector", first_2, select_first); 87 | assert(word3 == "torch"); 88 | 89 | auto [word4, definition4, offset4_2] = select_overlapping_word_from_dictionary("class", first_2, select_first); 90 | assert(word4 == "assault"); 91 | assert(offset4 == 2); 92 | 93 | auto [no_word, no_definition, no_offset] = select_overlapping_word_from_dictionary("class", {}, select_first); 94 | assert(no_word == ""); 95 | assert(no_offset == -1); 96 | 97 | std::string word("aaa"); 98 | auto [g1, d1, o1] = select_overlapping_word_from_dictionary(word, 99 | { {"a", "1"}, {"aaa", "1"}, {"aab", "1"}, {"aabb", "2"}, {"aabc", "2"}, {"abbc", "3"} }, 100 | select_first); 101 | assert(g1 == "aaa"); 102 | auto [g2, d2, o2] = select_overlapping_word_from_dictionary(word, 103 | { {"a", "1"}, {"aaaa", "1"}, {"aaab", "1"}, {"aaabb", "2"}, {"aaabc", "2"}, {"aabbc", "3"} }, 104 | select_first); 105 | assert(g2 == "aaaa"); 106 | 107 | auto select_last = [](auto lb, auto ub, auto dest) { 108 | *dest = *(--ub); 109 | }; 110 | auto [g1b, d1b, o1b] = select_overlapping_word_from_dictionary(word, 111 | { {"a", "1"}, {"aaa", "1"}, {"aab", "1"}, {"aabb", "2"}, {"aabc", "2"}, {"abbc", "3"} }, 112 | select_last); 113 | assert(g1b == "aabc"); 114 | auto [g2b, d2b, o2b] = select_overlapping_word_from_dictionary(word, 115 | { {"a", "1"}, {"aaaa", "1"}, {"aaab", "1"}, {"aaabb", "2"}, {"aaabc", "2"}, {"aabbc", "3"} }, 116 | select_last); 117 | assert(g2b == "aabbc"); 118 | } 119 | 120 | // Listing 7.1 Creating and displaying a map, along with some one liners considered in the text 121 | void warm_up() 122 | { 123 | std::map dictionary; 124 | dictionary["assume"] = "take for granted, take to be the case"; 125 | std::string new_value = dictionary["fictional"]; // inserts "" against fictional 126 | for (const auto & item : dictionary) 127 | { 128 | std::cout << item.first << " : " << item.second << '\n'; 129 | } 130 | // Extra ideas considered in the text 131 | dictionary["fictional"] = "made up"; // replaces "" 132 | // whereas insert tells us if something already exists 133 | auto result = dictionary.insert({ "insert", "place inside" }); 134 | std::cout << std::boolalpha << result.first->first << " added? " << result.second << " definition: " << result.first->second << '\n'; 135 | auto next_result = dictionary.insert({ "fictional", "not factual" }); 136 | std::cout << std::boolalpha << next_result.first->first << " added? " << next_result.second << " definition: " << next_result.first->second << '\n'; 137 | } 138 | 139 | // Listing 7.2 Using structure bindings to access map items 140 | void structure_bindings() 141 | { 142 | std::map dictionary; 143 | dictionary["assume"] = "take for granted, take to be the case"; 144 | std::string new_word = dictionary["fictional"]; 145 | for (const auto & [key, value] : dictionary) 146 | { 147 | std::cout << key << " : " << value << '\n'; 148 | } 149 | dictionary["fictional"] = "made up"; // replaces "" 150 | auto [it, result] = dictionary.insert({ "insert", "place inside" }); 151 | std::cout << std::boolalpha << it->first << " added? " << result << " definition: " << it->second << '\n'; 152 | auto [next_it, next_result] = dictionary.insert({ "fictional", "not factual" }); 153 | std::cout << std::boolalpha << next_it->first << " added? " << next_result << " definition: " << it->second << '\n'; 154 | } 155 | 156 | // Listing 7.15, Proper answer smash game but shown directly in main in the text 157 | void full_game() 158 | { 159 | using namespace smashing; 160 | const auto dictionary = load_dictionary(R"(dictionary.csv)"); 161 | const auto keywords = load_dictionary(R"(keywords.csv)"); 162 | answer_smash(keywords, dictionary); 163 | } 164 | 165 | // Listing 7.7 Play the first version of answer smash 166 | void hard_coded_game() 167 | { 168 | const std::map keywords{ 169 | {"char", "type for character representation which can be most" 170 | "efficiently processed on the target system"}, 171 | {"class", "user defined type with private members by default"}, 172 | {"struct", "user defined type with public members by default"}, 173 | {"vector", "sequential container supporting dynamic resizing"}, 174 | {"template", "family of classes or functions parameterized by one or more parameters"}, 175 | }; 176 | 177 | const std::map dictionary{ 178 | {"assume", "take for granted, take to be the case"}, 179 | {"harsh", "coarse, large-grained or rough to the touch"}, 180 | {"table", "piece of furniture"}, 181 | {"tease", "mock, make fun of"}, 182 | {"torch", "lit stick carried in one's hand"}, 183 | }; 184 | smashing::simple_answer_smash(keywords, dictionary); 185 | } 186 | 187 | int main() 188 | { 189 | check_properties(); 190 | 191 | std::cout << "Warm up\n\n"; 192 | warm_up(); 193 | std::cout << "\n\n"; 194 | 195 | std::cout << "Hard coded game\n\n"; 196 | hard_coded_game(); 197 | 198 | std::cout << "Full game\n\n"; 199 | full_game(); 200 | } -------------------------------------------------------------------------------- /Chapter8/Chapter8.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {3a4a2440-7ec2-4163-87fb-fad8e87f64aa} 25 | Chapter8 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | /std:c++latest %(AdditionalOptions) 80 | 81 | 82 | Console 83 | true 84 | 85 | 86 | 87 | 88 | Level3 89 | true 90 | true 91 | true 92 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 93 | true 94 | 95 | 96 | Console 97 | true 98 | true 99 | true 100 | 101 | 102 | 103 | 104 | Level3 105 | true 106 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 107 | true 108 | 109 | 110 | Console 111 | true 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | true 119 | true 120 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 121 | true 122 | 123 | 124 | Console 125 | true 126 | true 127 | true 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /Chapter8/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | 16 | // Listing 8.1 Read an optional zero or one 17 | std::optional read_number(std::istream& in) 18 | { 19 | std::string line; 20 | std::getline(in, line); 21 | if (line == "0") { 22 | return { 0 }; 23 | } 24 | else if (line == "1") { 25 | return { 1 }; 26 | } 27 | return {}; 28 | } 29 | 30 | // Listing 8.2 A pennies game 31 | void pennies_game() 32 | { 33 | int player_wins = 0; 34 | int turns = 0; 35 | std::mt19937 gen{ std::random_device{}() }; 36 | std::uniform_int_distribution dist(0, 1); 37 | 38 | std::cout << "Select 0 or 1 at random and press enter.\n"; 39 | std::cout << "If the computer predicts your guess it wins.\n"; 40 | while (true) 41 | { 42 | const int prediction = dist(gen); 43 | 44 | auto input = read_number(std::cin); 45 | if (!input) 46 | { 47 | break; 48 | } 49 | const int player_choice = input.value(); 50 | 51 | ++turns; 52 | std::cout << "You pressed " << player_choice << ", I guessed " << prediction << '\n'; 53 | 54 | if (player_choice != prediction) 55 | { 56 | ++player_wins; 57 | } 58 | } 59 | std::cout << "you win " << player_wins << '\n' 60 | << "I win " << turns - player_wins << '\n'; 61 | } 62 | 63 | // Listing 8.3 Three possible choices and outcomes 64 | enum class Choice 65 | { 66 | Same, 67 | Change, 68 | Shrug, 69 | }; 70 | 71 | enum class Outcome 72 | { 73 | Lose, 74 | Win, 75 | Unset, 76 | }; 77 | 78 | using state_t = std::tuple; 79 | using last_choices_t = std::pair; 80 | 81 | // Listing 8.5 Specializing std::hash for our state tuple 82 | template<> 83 | struct std::hash 84 | { 85 | std::size_t operator()(state_t const& state) const noexcept 86 | { 87 | std::size_t h1 = std::hash{}(std::get<0>(state)); 88 | std::size_t h2 = std::hash{}(std::get<1>(state)); 89 | std::size_t h3 = std::hash{}(std::get<2>(state)); 90 | return h1 + (h2 << 1) + (h3 << 2); 91 | } 92 | }; 93 | 94 | // Listing 8.6 An initial state table 95 | std::unordered_map initial_state() 96 | { 97 | const auto unset = std::pair{ Choice::Shrug, Choice::Shrug }; 98 | return { 99 | { {Outcome::Lose, Choice::Same, Outcome::Lose}, unset }, 100 | { {Outcome::Lose, Choice::Same, Outcome::Win}, unset }, 101 | { {Outcome::Lose, Choice::Change, Outcome::Lose}, unset }, 102 | { {Outcome::Lose, Choice::Change, Outcome::Win}, unset }, 103 | { {Outcome::Win, Choice::Same, Outcome::Lose}, unset }, 104 | { {Outcome::Win, Choice::Same, Outcome::Win}, unset }, 105 | { {Outcome::Win, Choice::Change, Outcome::Lose}, unset }, 106 | { {Outcome::Win, Choice::Change, Outcome::Win}, unset }, 107 | }; 108 | } 109 | 110 | // Listing 8.7 Class to track the game's state 111 | class State 112 | { 113 | std::unordered_map state_lookup = initial_state(); 114 | public: 115 | // Listing 8.8 Find the choices or return two shrugs 116 | last_choices_t choices(const state_t& key) const 117 | { 118 | if (auto it = state_lookup.find(key); it!=state_lookup.end()) 119 | { 120 | return it->second; 121 | } 122 | else 123 | { 124 | return { Choice::Shrug, Choice::Shrug }; 125 | } 126 | } 127 | // Listing 8.9 Update choices for valid keys 128 | void update(const state_t& key, const Choice& turn_changed) 129 | { 130 | if (auto it = state_lookup.find(key); it != state_lookup.end()) 131 | { 132 | const auto [prev2, prev1] = it->second; 133 | last_choices_t value{ prev1, turn_changed }; 134 | it->second = value; 135 | } 136 | } 137 | }; 138 | 139 | // Listing 8.10 Choice from state 140 | Choice prediction_method(const last_choices_t& choices) 141 | { 142 | if (choices.first == choices.second) 143 | { 144 | return choices.first; 145 | } 146 | else 147 | { 148 | return Choice::Shrug; 149 | } 150 | } 151 | 152 | // Listing 8.11 A mind-reading class 153 | template T, typename U> 154 | class MindReader { 155 | State state_table; 156 | 157 | T generator; 158 | U distribution; 159 | 160 | int prediction = flip(); 161 | 162 | state_t state{Outcome::Unset, Choice::Shrug, Outcome::Unset}; 163 | int previous_go = -1; 164 | 165 | // Listing 8.12 Update the prediction 166 | bool update_prediction(int player_choice) 167 | { 168 | bool guessing = false; 169 | Choice option = prediction_method(state_table.choices(state)); 170 | switch (option) 171 | { 172 | case Choice::Shrug: 173 | prediction = flip(); 174 | guessing = true; 175 | break; 176 | case Choice::Change: 177 | prediction = player_choice ^ 1; 178 | break; 179 | case Choice::Same: 180 | prediction = player_choice; 181 | break; 182 | } 183 | return guessing; 184 | } 185 | 186 | int flip() 187 | { 188 | return distribution(generator); 189 | } 190 | 191 | public: 192 | MindReader(T gen, U dis) 193 | : generator(gen), distribution(dis) 194 | { 195 | } 196 | 197 | int get_prediction() const 198 | { 199 | return prediction; 200 | } 201 | 202 | // Listing 8.13 The mind reader's update method 203 | bool update(int player_choice) 204 | { 205 | const Choice turn_changed = player_choice == previous_go ? Choice::Same : Choice::Change; 206 | state_table.update(state, turn_changed); 207 | 208 | previous_go = player_choice; 209 | state = {std::get<2>(state), turn_changed, (player_choice != prediction) ? Outcome::Win : Outcome::Lose}; 210 | 211 | return update_prediction(player_choice); 212 | } 213 | 214 | }; 215 | 216 | // Listing 8.6 Check we have no hash collisions (and more besides) 217 | void check_properties() 218 | { 219 | // No bucket clashes 220 | std::unordered_map states = initial_state(); 221 | for (size_t bucket = 0; bucket < states.bucket_count(); bucket++) 222 | { 223 | auto bucket_size = states.bucket_size(bucket); 224 | assert(bucket_size <= 1); 225 | } 226 | 227 | { 228 | MindReader mr([]() { return 0; }, [](auto gen) { return gen(); }); 229 | assert(mr.update(0)); // guesses first 230 | assert(mr.update(0)); // second is a guess too 231 | } 232 | 233 | assert(prediction_method({ Choice::Shrug, Choice::Shrug }) == Choice::Shrug); 234 | assert(prediction_method({ Choice::Shrug, Choice::Change }) == Choice::Shrug); 235 | assert(prediction_method({ Choice::Shrug, Choice::Same }) == Choice::Shrug); 236 | assert(prediction_method({ Choice::Change, Choice::Shrug }) == Choice::Shrug); 237 | assert(prediction_method({ Choice::Same, Choice::Shrug }) == Choice::Shrug); 238 | assert(prediction_method({ Choice::Change, Choice::Change }) == Choice::Change); 239 | assert(prediction_method({ Choice::Same, Choice::Same }) == Choice::Same); 240 | assert(prediction_method({ Choice::Change, Choice::Same }) == Choice::Shrug); 241 | assert(prediction_method({ Choice::Same, Choice::Change }) == Choice::Shrug); 242 | 243 | State s; 244 | auto got1 = s.choices({ Outcome::Unset, Choice::Shrug, Outcome::Unset }); 245 | assert(got1.first == Choice::Shrug); 246 | assert(got1.second == Choice::Shrug); 247 | auto got2 = s.choices({ Outcome::Lose, Choice::Same, Outcome::Unset }); 248 | assert(got2.first == Choice::Shrug); 249 | assert(got2.second == Choice::Shrug); 250 | auto got3 = s.choices({ Outcome::Win, Choice::Change, Outcome::Unset }); 251 | assert(got3.first == Choice::Shrug); 252 | assert(got3.second == Choice::Shrug); 253 | 254 | { 255 | // Listing 6.12 had a RandomBlob we tested, using a lambda to stub out the random function 256 | // This always returns 0 257 | MindReader mr([]() { return 0; }, [](auto gen) { return gen(); }); 258 | assert( mr.update(0)); //flip first two goes 259 | assert( mr.update(0)); //flip first two goes 260 | // The random generator always returns zero 261 | // it guesses first 262 | // state is 263 | // lose, same, lose 264 | // but without two matching next choices 265 | assert( mr.update(0)); 266 | // now 267 | // lose, same, lose -> -1 ,lose 268 | // so when we decide 0 it stops guessing 269 | // now the state is 270 | // lose, same, lose -> lose ,lose 271 | // so it will predict a 0 next 272 | assert(!mr.update(0)); 273 | assert( mr.get_prediction() == 0); 274 | assert(!mr.update(0)); 275 | assert( mr.get_prediction() == 0); 276 | assert(!mr.update(0)); 277 | assert( mr.get_prediction() == 0); 278 | assert(!mr.update(0)); 279 | assert( mr.get_prediction() == 0); 280 | assert(!mr.update(0)); 281 | assert( mr.get_prediction() == 0); 282 | } 283 | } 284 | 285 | // Listing 8.14 A mind reading game 286 | void mind_reader() 287 | { 288 | int turns = 0; 289 | int player_wins = 0; 290 | int guessing = 0; 291 | 292 | std::mt19937 gen{ std::random_device{}() }; 293 | std::uniform_int_distribution dist{ 0, 1 }; 294 | MindReader mr(gen, dist); 295 | 296 | std::cout << "Select 0 or 1 at random and press enter.\n"; 297 | std::cout << "If the computer predicts your guess it wins\n"; 298 | std::cout << "and it can now read your mind.\n"; 299 | while (true) 300 | { 301 | const int prediction = mr.get_prediction(); 302 | 303 | auto input = read_number(std::cin); 304 | if (!input) 305 | { 306 | break; 307 | } 308 | const int player_choice = input.value(); 309 | 310 | ++turns; 311 | std::cout << "You pressed " << player_choice 312 | << ", I guessed " << prediction << '\n'; 313 | 314 | if (player_choice != prediction) 315 | { 316 | ++player_wins; 317 | } 318 | if (mr.update(player_choice)) 319 | { 320 | ++guessing; 321 | } 322 | } 323 | std::cout << "you win " << player_wins << '\n' 324 | << "machine guessed " << guessing << " times" << '\n' 325 | << "machine won " << (turns - player_wins) << '\n'; 326 | } 327 | 328 | // Listing 8.18 Customer "deleter" 329 | template 330 | struct coro_deleter 331 | { 332 | void operator()(Promise* promise) const noexcept 333 | { 334 | auto handle = std::coroutine_handle::from_promise(*promise); 335 | if (handle) 336 | handle.destroy(); 337 | } 338 | }; 339 | 340 | template 341 | using promise_ptr = std::unique_ptr>; 342 | 343 | 344 | // Listing 8.17, 8.20 and 8.21 The coroutine's Task and promise_type 345 | struct Task 346 | { 347 | // Listing 8.19 Our promise type 348 | struct promise_type 349 | { 350 | std::pair choice_and_prediction; 351 | 352 | Task get_return_object() 353 | { 354 | return Task(this); 355 | } 356 | std::suspend_never initial_suspend() noexcept { return {}; } 357 | std::suspend_always final_suspend() noexcept { return {}; } 358 | void unhandled_exception() {} 359 | std::suspend_always yield_value(std::pair got) 360 | { 361 | choice_and_prediction = got; 362 | return {}; 363 | } 364 | 365 | void return_void() { } 366 | }; 367 | 368 | std::pair choice_and_prediction() const 369 | { 370 | return promise->choice_and_prediction; 371 | } 372 | bool done() const 373 | { 374 | auto handle = std::coroutine_handle::from_promise(*promise); 375 | return handle.done(); 376 | } 377 | void next() 378 | { 379 | auto handle = std::coroutine_handle::from_promise(*promise); 380 | handle(); 381 | } 382 | private: 383 | promise_ptr promise; 384 | Task(promise_type* p) : promise(p) {} 385 | }; 386 | 387 | // Listing 8.16 Our first coroutine 388 | Task coroutine_game() 389 | { 390 | std::mt19937 gen{ std::random_device{}() }; 391 | std::uniform_int_distribution dist{ 0, 1 }; 392 | MindReader mr(gen, dist); 393 | 394 | while (true) 395 | { 396 | auto input = read_number(std::cin); 397 | if (!input) 398 | { 399 | co_return; 400 | } 401 | int player_choice = input.value(); 402 | co_yield{ player_choice , mr.get_prediction() }; 403 | mr.update(player_choice); 404 | } 405 | } 406 | 407 | // Listing 8.22 A coroutine version of a mind reader 408 | void coroutine_minder_reader() 409 | { 410 | int turns = 0; 411 | int player_wins = 0; 412 | 413 | std::cout << "Select 0 or 1 at random and press enter.\n"; 414 | std::cout << "If the computer predicts your guess it wins\nand it can now read your mind.\n"; 415 | 416 | Task game = coroutine_game(); 417 | 418 | while (!game.done()) 419 | { 420 | auto [player_choice, prediction] = game.choice_and_prediction(); 421 | ++turns; 422 | std::cout << "You pressed " << player_choice << ", I guessed " << prediction << '\n'; 423 | 424 | if (player_choice != prediction) 425 | { 426 | ++player_wins; 427 | } 428 | game.next(); 429 | } 430 | std::cout << "you win " << player_wins << '\n' 431 | << "machine won " << (turns - player_wins) << '\n'; 432 | } 433 | 434 | int main() 435 | { 436 | check_properties(); 437 | 438 | pennies_game(); 439 | // Choose one version of the mind reader (or play both if you want): 440 | mind_reader(); 441 | //coroutine_minder_reader(); 442 | } -------------------------------------------------------------------------------- /Chapter9/Chapter9.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {2279a9b4-2875-47ab-9e97-3f51fe473e3b} 25 | Chapter9 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | /std:c++latest %(AdditionalOptions) 80 | 81 | 82 | Console 83 | true 84 | 85 | 86 | 87 | 88 | Level3 89 | true 90 | true 91 | true 92 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 93 | true 94 | 95 | 96 | Console 97 | true 98 | true 99 | true 100 | 101 | 102 | 103 | 104 | Level3 105 | true 106 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 107 | true 108 | 109 | 110 | Console 111 | true 112 | 113 | 114 | 115 | 116 | Level3 117 | true 118 | true 119 | true 120 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 121 | true 122 | 123 | 124 | Console 125 | true 126 | true 127 | true 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /Chapter9/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | using Reel = std::vector; 21 | 22 | // Listing 9.1 Make the first few triangle numbers 23 | // constexpr added in section 9.2 24 | constexpr std::vector make_triangle_numbers(int count) 25 | { 26 | std::vector numbers(count); 27 | std::iota(numbers.begin(), numbers.end(), 1); 28 | std::partial_sum(numbers.begin(), numbers.end(), numbers.begin()); 29 | return numbers; 30 | } 31 | 32 | // Listing 9.5 and 9.6 33 | void demo_further_properties() 34 | { 35 | const int count = 20; 36 | const auto triangle_numbers = make_triangle_numbers(count); 37 | std::vector odd_or_even; 38 | std::ranges::transform(triangle_numbers, 39 | std::back_inserter(odd_or_even), 40 | [](int i) { return i % 2 ? '.' : '*'; }); 41 | std::ranges::copy(odd_or_even, std::ostream_iterator(std::cout, " ")); 42 | std::cout << '\n'; 43 | 44 | std::map last_digits; 45 | for (int number: triangle_numbers) 46 | { 47 | ++last_digits[number % 10]; 48 | } 49 | std::cout << "Tallies of the final digits of the first 20 triangle numbers\n"; 50 | for (const auto& [key, value] : last_digits) 51 | { 52 | std::cout << key << " : " << value << '\n'; 53 | } 54 | } 55 | 56 | // Listing 9.7 Setup reels 57 | template::iterator, std::vector::iterator> T> 58 | constexpr std::vector make_reels(int numbers, int number_of_reels, T shuffle) 59 | { 60 | std::vector reels(number_of_reels, make_triangle_numbers(numbers)); 61 | 62 | for (auto& reel : reels) 63 | { 64 | shuffle(reel.begin(), reel.end()); 65 | } 66 | return reels; 67 | } 68 | 69 | // Listing 9.8 Display reels 70 | void show_reels(std::ostream& s, const std::vector& left, const std::vector& middle, const std::vector& right) 71 | { 72 | s << std::format(" {:>3} {:>3} {:>3}\n", left.back(), middle.back(), right.back()); 73 | s << std::format("-{:>3} {:>3} {:>3}-\n", left[0], middle[0], right[0]); 74 | s << std::format(" {:>3} {:>3} {:>3}\n", left[1], middle[1], right[1]); 75 | } 76 | 77 | // Listing 9.9 Calculate payout 78 | int calculate_payout_v1(int left, int middle, int right) 79 | { 80 | int payout = 0; 81 | if (left == middle && middle == right) 82 | { 83 | payout = 2; 84 | } 85 | else if (left == middle || middle == right || left == right) 86 | { 87 | payout = 1; 88 | } 89 | return payout; 90 | } 91 | 92 | // Listing 9.12 Finding frequencies using a parameter pack 93 | // We considered 94 | //template 95 | //std::map frequencies(Ts... numbers) 96 | // and then 97 | //std::map frequencies(auto ...numbers) 98 | // but settled on 99 | std::map frequencies(std::convertible_to auto... numbers) 100 | { 101 | std::map counter{}; 102 | for (int i : { static_cast(numbers)... }) 103 | counter[i]++; 104 | return counter; 105 | } 106 | 107 | // Listing 9.13 A fairer payout 108 | int calculate_payout(int left, int middle, int right) 109 | { 110 | std::map counter = frequencies(left, middle, right); 111 | auto it = std::max_element(counter.begin(), counter.end(), 112 | [](auto it1, auto it2) { return it1.second < it2.second; }); 113 | if (it != counter.end()) 114 | { 115 | int digit = it->first; 116 | size_t count = it->second; 117 | if (digit == 8 || digit == 3) 118 | { 119 | constexpr std::array value = { 0, 0, 10, 250 }; 120 | return value[count]; 121 | } 122 | else 123 | { 124 | constexpr std::array value = { 0, 0, 1, 15 }; 125 | return value[count]; 126 | } 127 | } 128 | return 0; 129 | } 130 | 131 | // Listing 9.10 A simple slot machine 132 | void triangle_machine_spins_only() 133 | { 134 | constexpr int numbers = 20; 135 | constexpr size_t number_of_reels = 3u; 136 | std::random_device rd; 137 | std::mt19937 gen{ rd() }; 138 | auto shuffle = [&gen](auto begin, auto end) { std::shuffle(begin, end, gen); }; 139 | std::vector reels = make_reels(numbers, number_of_reels, shuffle); 140 | 141 | std::uniform_int_distribution dist(1, numbers - 1); 142 | int credit = 1; 143 | while (true) 144 | { 145 | show_reels(std::cout, reels[0], reels[1], reels[2]); 146 | const int payout = calculate_payout_v1(reels[0][0]%10, reels[1][0]%10, reels[2][0]%10); 147 | --credit; 148 | credit += payout; 149 | std::cout << "won " << payout << " credit = " << credit << '\n'; 150 | 151 | std::string response; 152 | std::getline(std::cin, response); 153 | if (response != "") 154 | { 155 | break; 156 | } 157 | for (auto& reel : reels) 158 | { 159 | std::rotate(reel.begin(), reel.begin() + dist(gen), reel.end()); 160 | } 161 | } 162 | } 163 | 164 | // Listing 9.11 Fold example 165 | template 166 | auto add(const Ts &... tail) 167 | { 168 | return (... + tail); 169 | // or 170 | // return (tail + ...); 171 | } 172 | 173 | // Listing 9.14 Allow more options 174 | struct Hold {}; 175 | struct Nudge {}; 176 | struct Spin {}; 177 | using options = std::variant; 178 | 179 | // Listing 9.15 Three spins for Enter 180 | constexpr std::optional> parse_enter(const std::string& response) 181 | { 182 | if (response.empty()) 183 | { 184 | return std::vector{Spin{}, Spin{}, Spin{}}; 185 | } 186 | else 187 | { 188 | return {}; 189 | } 190 | } 191 | 192 | // Listing 9.16 Check for Enter pressed 193 | std::optional> get_enter() 194 | { 195 | std::cout << "Enter to play\n"; 196 | std::string response; 197 | std::getline(std::cin, response); 198 | auto got = parse_enter(response); 199 | if (!got) 200 | { 201 | std::cout << "Are you sure you want to quit? Press Enter to keep playing\n"; 202 | std::getline(std::cin, response); 203 | got = parse_enter(response); 204 | } 205 | return got; 206 | } 207 | 208 | // Listing 9.17 Map a character to an action 209 | constexpr std::optional map_input(char c) 210 | { 211 | switch (c) 212 | { 213 | case 'h': 214 | return Hold{}; 215 | break; 216 | case 'n': 217 | return Nudge{}; 218 | break; 219 | case 's': 220 | return Spin{}; 221 | break; 222 | } 223 | return {}; 224 | } 225 | 226 | // Listing 9.18 Check for holds, nudges or spins 227 | constexpr std::optional> parse_input(const std::string & response) 228 | { 229 | std::vector choice; 230 | for (char c : response) 231 | { 232 | auto first = map_input(c); 233 | if (first) 234 | { 235 | choice.push_back(first.value()); 236 | } 237 | else 238 | { 239 | return {}; 240 | } 241 | } 242 | return choice.empty() ? std::vector{Spin{}, Spin{}, Spin{}} : choice; 243 | } 244 | 245 | // Listing 9.19 Check for options 246 | std::optional> get_input(size_t expected_length) 247 | { 248 | std::cout << "Hold (h), spin(s), nudge(n) or Enter for spins\n"; 249 | std::string response; 250 | std::getline(std::cin, response); 251 | auto got = parse_input(response); 252 | if (!got || response.length()> expected_length) 253 | { 254 | std::cout << "Are you sure you want to quit?\n"; 255 | std::getline(std::cin, response); 256 | got = parse_input(response); 257 | } 258 | return got; 259 | } 260 | 261 | 262 | // Listing 9.21 Bring operator() into scope in a class 263 | // called Overload in the text 264 | template 265 | struct Overload1 : T { 266 | using T::operator(); 267 | }; 268 | 269 | // for clang 270 | template 271 | Overload1(T) -> Overload1; 272 | 273 | 274 | // Listing 9.22 The Overload pattern 275 | template 276 | struct Overload : Ts... { 277 | using Ts::operator()...; 278 | }; 279 | 280 | // for clang 281 | template 282 | Overload(Ts...) -> Overload; 283 | 284 | // Listing 9.24 Move the reels 285 | template 286 | void move_reel(std::vector& reel, options opt, T random_fn) 287 | { 288 | auto RollMethod = Overload{ 289 | [](Hold) {}, 290 | [&reel](Nudge) { std::rotate(reel.begin(), reel.begin() + 1, reel.end()); }, 291 | [&reel, &random_fn](Spin) { std::rotate(reel.begin(), reel.begin() + random_fn(), reel.end()); }, 292 | }; 293 | 294 | std::visit(RollMethod, opt); 295 | } 296 | 297 | // Listing 9.25 An improved triangle number machine 298 | void triangle_machine() 299 | { 300 | constexpr int numbers = 20; 301 | constexpr size_t number_of_reels = 3u; 302 | std::random_device rd; 303 | std::mt19937 gen{ rd() }; 304 | auto shuffle = [&gen](auto begin, auto end) { std::shuffle(begin, end, gen); }; 305 | std::vector reels = make_reels(numbers, number_of_reels, shuffle); 306 | 307 | std::uniform_int_distribution dist(1, numbers - 1); 308 | auto random_fn = [&gen, &dist]() { return dist(gen); }; 309 | int credit = 2; 310 | while (true) 311 | { 312 | show_reels(std::cout, reels[0], reels[1], reels[2]); 313 | const int won = calculate_payout(reels[0][0] % 10, reels[1][0] % 10, reels[2][0] % 10); 314 | credit -= 2; // Note two credits per game now 315 | credit += won; 316 | std::cout << "won " << won << " credit = " << credit << '\n'; 317 | 318 | std::optional> choice = won ? get_enter() : get_input(number_of_reels); 319 | if (!choice) 320 | { 321 | break; 322 | } 323 | 324 | // Note - if std::views::zip doesn't compile, use the for loop instead or Range-v3, https://ericniebler.github.io/range-v3/ 325 | for (auto [reel, option] : std::views::zip(reels, choice.value())) 326 | { 327 | move_reel(reel, option, random_fn); 328 | } 329 | // You might need to use this instead of the view's zip 330 | //for (size_t i = 0; i < reels.size(); ++i) 331 | //{ 332 | // move_reel(reels[i], choice.value()[i], random_fn); 333 | //} 334 | } 335 | } 336 | 337 | // Listing 9.2 and 9.3 Test our triangle numbers 338 | void check_properties() 339 | { 340 | const int count = 20; 341 | const auto triangle_numbers = make_triangle_numbers(count); 342 | std::vector diffs(count); 343 | std::adjacent_difference(triangle_numbers.begin(), triangle_numbers.end(), diffs.begin()); 344 | std::vector numbers(count); 345 | std::iota(numbers.begin(), numbers.end(), 1); 346 | assert(numbers == diffs); 347 | std::adjacent_difference(diffs.begin(), diffs.end(), diffs.begin()); 348 | assert(std::all_of(diffs.begin(), diffs.end(), [](int x) { return x == 1; })); 349 | // parallel request 350 | assert(std::count(std::execution::par, diffs.begin(), diffs.end(), 1) == count); 351 | 352 | // Check closed form n * (n+1)/2 353 | // either with a for loop 354 | for (size_t i = 0; i < triangle_numbers.size(); ++i) 355 | { 356 | const int n = i + 1; 357 | assert(triangle_numbers[i] == n * (n + 1) / 2); 358 | } 359 | // or an algo with a mutable lambda 360 | assert(std::all_of(triangle_numbers.begin(), triangle_numbers.end(), 361 | [n = 0](int x) mutable 362 | { 363 | ++n; 364 | return x == n * (n + 1) / 2; 365 | } 366 | )); 367 | 368 | assert(calculate_payout_v1(0, 1, 3) == 0); 369 | assert(calculate_payout_v1(0, 0, 3) == 1); 370 | assert(calculate_payout_v1(0, 3, 3) == 1); 371 | assert(calculate_payout_v1(3, 0, 3) == 1); 372 | assert(calculate_payout_v1(3, 3, 0) == 1); 373 | assert(calculate_payout_v1(0, 0, 0) == 2); 374 | assert(calculate_payout_v1(3, 3, 3) == 2); 375 | assert(calculate_payout_v1(8, 8, 8) == 2); 376 | 377 | assert(calculate_payout(0, 1, 3) == 0); 378 | assert(calculate_payout(0, 0, 3) == 1); 379 | assert(calculate_payout(0, 3, 3) == 10); 380 | assert(calculate_payout(3, 0, 3) == 10); 381 | assert(calculate_payout(3, 3, 0) == 10); 382 | assert(calculate_payout(0, 0, 0) == 15); 383 | assert(calculate_payout(3, 3, 3) == 250); 384 | assert(calculate_payout(8, 8, 8) == 250); 385 | 386 | constexpr auto no_op = [](auto begin, auto end) { }; 387 | static_assert(make_reels(1, 1, no_op).size() == 1); 388 | 389 | std::vector v{1, 2, 3, 4, 5}; 390 | std::rotate(v.begin(), v.begin() + 3, v.end()); 391 | assert(v[0] == 4); 392 | std::rotate(v.begin(), v.begin() + 2, v.end()); 393 | assert(v[0] == 1); 394 | 395 | static_assert( parse_enter("").has_value()); 396 | static_assert(!parse_enter("q").has_value()); 397 | static_assert( parse_input("hhh").has_value()); 398 | static_assert(!parse_input("q").has_value()); 399 | 400 | // assert(0 == add()); //won't compile unless we use 0 + ... + tail, but that stops the string use case compiling 401 | assert(1 == add(1)); 402 | assert(6 == add(1, 2, 3)); 403 | using namespace std::literals; 404 | assert(add("Hello"s, "again"s, "world"s)=="Helloagainworld"s); 405 | 406 | auto overload = Overload{ []() { return 0; } }; 407 | assert(overload() == 0); 408 | } 409 | 410 | int main() 411 | { 412 | check_properties(); 413 | demo_further_properties(); 414 | 415 | triangle_machine_spins_only(); 416 | 417 | std::cout << "New game with Hold (h), spin(s), nudge(n) or Enter for spins\n"; 418 | triangle_machine(); 419 | } -------------------------------------------------------------------------------- /Code.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.3.32922.545 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter2.1", "Chapter2.1\Chapter2.1.vcxproj", "{273C3030-6833-475F-AB2F-6E8BF90346DA}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter2.2", "Chapter2.2\Chapter2.2.vcxproj", "{740DA552-2257-441E-8C77-EF5A9CE71A34}" 9 | EndProject 10 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter3.1", "Chapter3\Chapter3.vcxproj", "{CB04CC30-C39B-4113-8A17-79A38CE001B4}" 11 | EndProject 12 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter1", "Chapter1\Chapter1.vcxproj", "{B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}" 13 | EndProject 14 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter4", "Chapter4\Chapter4.vcxproj", "{7F372FE2-1C32-42E9-BD2B-D792D14AA41D}" 15 | EndProject 16 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter5", "Chapter5\Chapter5.vcxproj", "{D89BF596-102A-45C9-9938-90F3AF03A405}" 17 | EndProject 18 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter6", "Chapter6\Chapter6.vcxproj", "{2707B232-4D22-487E-80EB-4E5BD325AA2A}" 19 | EndProject 20 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter7", "Chapter7\Chapter7.vcxproj", "{A37213E0-CC6C-40D3-B66C-6FA879DF9508}" 21 | EndProject 22 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter8", "Chapter8\Chapter8.vcxproj", "{3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}" 23 | EndProject 24 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Chapter9", "Chapter9\Chapter9.vcxproj", "{2279A9B4-2875-47AB-9E97-3F51FE473E3B}" 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|x64 = Debug|x64 29 | Debug|x86 = Debug|x86 30 | Release|x64 = Release|x64 31 | Release|x86 = Release|x86 32 | EndGlobalSection 33 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 34 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Debug|x64.ActiveCfg = Debug|x64 35 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Debug|x64.Build.0 = Debug|x64 36 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Debug|x86.ActiveCfg = Debug|Win32 37 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Debug|x86.Build.0 = Debug|Win32 38 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Release|x64.ActiveCfg = Release|x64 39 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Release|x64.Build.0 = Release|x64 40 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Release|x86.ActiveCfg = Release|Win32 41 | {273C3030-6833-475F-AB2F-6E8BF90346DA}.Release|x86.Build.0 = Release|Win32 42 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Debug|x64.ActiveCfg = Debug|x64 43 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Debug|x64.Build.0 = Debug|x64 44 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Debug|x86.ActiveCfg = Debug|Win32 45 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Debug|x86.Build.0 = Debug|Win32 46 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Release|x64.ActiveCfg = Release|x64 47 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Release|x64.Build.0 = Release|x64 48 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Release|x86.ActiveCfg = Release|Win32 49 | {740DA552-2257-441E-8C77-EF5A9CE71A34}.Release|x86.Build.0 = Release|Win32 50 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Debug|x64.ActiveCfg = Debug|x64 51 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Debug|x64.Build.0 = Debug|x64 52 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Debug|x86.ActiveCfg = Debug|Win32 53 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Debug|x86.Build.0 = Debug|Win32 54 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Release|x64.ActiveCfg = Release|x64 55 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Release|x64.Build.0 = Release|x64 56 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Release|x86.ActiveCfg = Release|Win32 57 | {CB04CC30-C39B-4113-8A17-79A38CE001B4}.Release|x86.Build.0 = Release|Win32 58 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Debug|x64.ActiveCfg = Debug|x64 59 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Debug|x64.Build.0 = Debug|x64 60 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Debug|x86.ActiveCfg = Debug|Win32 61 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Debug|x86.Build.0 = Debug|Win32 62 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Release|x64.ActiveCfg = Release|x64 63 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Release|x64.Build.0 = Release|x64 64 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Release|x86.ActiveCfg = Release|Win32 65 | {B6EE4E15-5A1F-4B4F-A52C-667AE934EF7E}.Release|x86.Build.0 = Release|Win32 66 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Debug|x64.ActiveCfg = Debug|x64 67 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Debug|x64.Build.0 = Debug|x64 68 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Debug|x86.ActiveCfg = Debug|Win32 69 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Debug|x86.Build.0 = Debug|Win32 70 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Release|x64.ActiveCfg = Release|x64 71 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Release|x64.Build.0 = Release|x64 72 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Release|x86.ActiveCfg = Release|Win32 73 | {7F372FE2-1C32-42E9-BD2B-D792D14AA41D}.Release|x86.Build.0 = Release|Win32 74 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Debug|x64.ActiveCfg = Debug|x64 75 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Debug|x64.Build.0 = Debug|x64 76 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Debug|x86.ActiveCfg = Debug|Win32 77 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Debug|x86.Build.0 = Debug|Win32 78 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Release|x64.ActiveCfg = Release|x64 79 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Release|x64.Build.0 = Release|x64 80 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Release|x86.ActiveCfg = Release|Win32 81 | {D89BF596-102A-45C9-9938-90F3AF03A405}.Release|x86.Build.0 = Release|Win32 82 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Debug|x64.ActiveCfg = Debug|x64 83 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Debug|x64.Build.0 = Debug|x64 84 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Debug|x86.ActiveCfg = Debug|Win32 85 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Debug|x86.Build.0 = Debug|Win32 86 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Release|x64.ActiveCfg = Release|x64 87 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Release|x64.Build.0 = Release|x64 88 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Release|x86.ActiveCfg = Release|Win32 89 | {2707B232-4D22-487E-80EB-4E5BD325AA2A}.Release|x86.Build.0 = Release|Win32 90 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Debug|x64.ActiveCfg = Debug|x64 91 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Debug|x64.Build.0 = Debug|x64 92 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Debug|x86.ActiveCfg = Debug|Win32 93 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Debug|x86.Build.0 = Debug|Win32 94 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Release|x64.ActiveCfg = Release|x64 95 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Release|x64.Build.0 = Release|x64 96 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Release|x86.ActiveCfg = Release|Win32 97 | {A37213E0-CC6C-40D3-B66C-6FA879DF9508}.Release|x86.Build.0 = Release|Win32 98 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Debug|x64.ActiveCfg = Debug|x64 99 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Debug|x64.Build.0 = Debug|x64 100 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Debug|x86.ActiveCfg = Debug|Win32 101 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Debug|x86.Build.0 = Debug|Win32 102 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Release|x64.ActiveCfg = Release|x64 103 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Release|x64.Build.0 = Release|x64 104 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Release|x86.ActiveCfg = Release|Win32 105 | {3A4A2440-7EC2-4163-87FB-FAD8E87F64AA}.Release|x86.Build.0 = Release|Win32 106 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Debug|x64.ActiveCfg = Debug|x64 107 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Debug|x64.Build.0 = Debug|x64 108 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Debug|x86.ActiveCfg = Debug|Win32 109 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Debug|x86.Build.0 = Debug|Win32 110 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Release|x64.ActiveCfg = Release|x64 111 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Release|x64.Build.0 = Release|x64 112 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Release|x86.ActiveCfg = Release|Win32 113 | {2279A9B4-2875-47AB-9E97-3F51FE473E3B}.Release|x86.Build.0 = Release|Win32 114 | EndGlobalSection 115 | GlobalSection(SolutionProperties) = preSolution 116 | HideSolutionNode = FALSE 117 | EndGlobalSection 118 | GlobalSection(ExtensibilityGlobals) = postSolution 119 | SolutionGuid = {BC909B9E-D965-4DF1-A3E7-E8FB3892D2F4} 120 | EndGlobalSection 121 | EndGlobal 122 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Code for [Learn C++ by Example](http://mng.bz/RZAa) 2 | 3 | The original working title was Bootstrap C++, hence this repo's name, then we considered C++ Bookcamp, and settled on Learn C+ by Example. 4 | 5 | The book is aimed at beginners who know C++ basics, coders coming back to the language, or current C++ developers missing out on everything the language has to offer. 6 | 7 | ![Buontempo-HI](https://github.com/doctorlove/BootstrapCpp/assets/613125/efe7ef13-8952-4598-a53d-53b59bd7b9ad) 8 | --------------------------------------------------------------------------------