├── LICENCE ├── README.md ├── adding_elements_strings ├── append.cc ├── insert1.cc ├── insert2.cc ├── insert_iterators.cc └── insert_iterators2.cc ├── addition_operators └── complex.cc ├── algorithms_overview └── find.cc ├── algorithms_with_if_versions ├── find_if.cc ├── find_if_n.cc └── find_if_not.cc ├── algorithms_with_predicates ├── pred_function_ptr.cc ├── pred_functor.cc └── sort.cc ├── assignment_operator_overview └── string.cc ├── associative_container_custom_types ├── book.cc ├── book_index.cc └── book_index.h ├── attributes ├── cpp11.cc ├── cpp14.cc ├── fallthrough.cc ├── maybe_used.cc ├── nodiscard.cc └── nodiscard_struct.cc ├── auto_keyword ├── auto_func.cc ├── auto_keyword.cc └── qualifiers.cc ├── base_and_derived_classes ├── constructors.cc ├── fighter_aeroplane.cc └── hierarchy.cc ├── basic_string_ops ├── constructors.cc └── substr.cc ├── binary_files └── binary.cc ├── binary_files_practical ├── bitmap.cc ├── bitmap.h └── main.cc ├── bind ├── bind.cc ├── bind_algo.cc ├── bound_lambda.cc ├── match.cc └── match_error.cc ├── bitsets ├── checks.cc ├── data_access.cc ├── member_operations.cc └── operations.cc ├── callable_objects └── function.cc ├── casting ├── c.cc ├── const_cast.cc └── static_cast.cc ├── catch_all_handlers └── catch_all.cc ├── character_fns ├── equal_strings.cc ├── isxyz.cc └── toupper.cc ├── chrono_clocks_and_time_points ├── sleep.cc └── timer.cc ├── chrono_duration_types ├── constructor.cc ├── conversion.cc ├── duration_cast.cc └── operations.cc ├── classes_and_templates ├── different_parameter.cc └── member_template.cc ├── compile_time_programming_overview ├── macro.cc └── traits.cc ├── constant_expressions ├── constant_expression.cc └── constexpr.cc ├── constexpr_functions └── constexpr_fn.cc ├── constexpr_if ├── constexpr_if.cc ├── if.cc ├── sfinae.cc └── specialization.cc ├── constexpr_if_examples ├── fibonacci_constexpr.cc ├── fibonacci_specialization.cc ├── parameter_pack_constexpr.cc └── parameter_pack_specialization.cc ├── constructors_in_modern_cpp ├── constructors.cc ├── default.cc ├── delegate.cc ├── init.cc └── inplace.cc ├── conversion_operators ├── explicit_bool.cc ├── explicit_constructor.cc ├── explicit_conversion.cc ├── implicit.cc ├── implicit2.cc └── surprise.cc ├── converting_between_strings_and_numbers ├── stod.cc ├── stoi.cc └── to_string.cc ├── conways_game_of_life_practical ├── ansi_escapes.cc ├── ansi_escapes.h ├── cell.cc ├── cell.h ├── grid.cc ├── grid.h ├── life.h └── main.cc ├── copy_and_swap └── string.cc ├── copy_constructor_overview └── string.cc ├── copy_elision ├── elide.cc ├── nvro.cc └── temp.cc ├── copying_algorithms ├── copy.cc ├── copy_if.cc └── copy_n.cc ├── custom_exception └── grade.cc ├── declaration_initialization ├── alias.cc ├── initialization.cc ├── initialization_contd.cc ├── nullptr.cc └── vector_vector.cc ├── decltype_keyword ├── decltype_auto.cc ├── lvalue_rvalue.cc ├── qualifiers.cc └── use_cases.cc ├── default_and_delete_keywords ├── delete.cc └── uncopyable.cc ├── deque └── deque.cc ├── emplace ├── emplace.cc ├── emplace_back.cc └── try_emplace.cc ├── equality_and_inequality_operators ├── main.cc ├── student.cc └── student.h ├── exception_mechanism └── rethrow.cc ├── exception_safe_class ├── string.cc └── string2.cc ├── exceptions_and_special_members └── throwing_constructor.cc ├── exceptions_introduction ├── handled.cc └── unhandled.cc ├── exceptions_workshop ├── at_vector.cc ├── error_codes.cc └── grade.cc ├── extern_templates ├── extern_int.h ├── extern_int1.cc ├── extern_int2.cc ├── extern_int_impls.cc ├── extern_template.h ├── extern_template1.cc ├── extern_template2.cc ├── extern_template_impls.cc ├── manual.h ├── manual1.cc └── manual2.cc ├── file_modes ├── append.cc └── important.txt ├── file_streams ├── read.cc ├── read_getline.cc ├── text.txt ├── text_out.txt └── write.cc ├── floating_point_output_formats ├── default.cc ├── fixed.cc ├── precision.cc └── scientific.cc ├── for_each_algorithm ├── for_each.cc └── for_each_ref.cc ├── forward_list └── forward_list.cc ├── forwarding_references ├── nested.cc └── template.cc ├── friend_keyword ├── delegate.cc ├── friend_class.cc └── friend_function.cc ├── function_arguments_and_move_semantics ├── const_lvalue.cc ├── rvalue_ref.cc ├── value.cc └── value_then_move.cc ├── function_call_operator ├── functor.cc ├── functor2.cc └── functor3.cc ├── function_pointer ├── function_pointer.cc └── function_pointer_func.cc ├── further_numeric_algorithms ├── adjacent_difference.cc ├── inner_product.cc └── partial_sum.cc ├── further_numeric_algos_contd ├── inner_product.cc └── inner_product_overload.cc ├── if_statements_and_switch_in_cpp17 ├── fallthrough.cc ├── if.cc └── switch.cc ├── inline_namespace ├── inline.cc ├── nested.cc ├── product.cc ├── version1.h └── version2.h ├── insert_iterators ├── back_insert.cc ├── insert.cc ├── invalid.cc └── istream.cc ├── interfaces_and_virtual_functions ├── abstract_base.cc ├── object_slicing.cc └── object_unsliced.cc ├── interfacing_to_c ├── add.cc ├── add.h ├── add_main.c ├── array.c ├── array.h └── array_main.cc ├── iterator_arithmetic_and_ranges ├── distance_advance.cc └── it_arith.cc ├── iterator_introduction ├── array_it.cc ├── string_it.cc ├── string_loop.cc └── vector_it.cc ├── lambda_expressions_and_capture ├── capture_functor.cc ├── capture_lambda.cc ├── mutable.cc ├── nocapture_lambda.cc └── non_local.cc ├── lambda_expressions_and_capture_contd ├── by_ref.cc ├── capture_functor.cc ├── capture_star_this.cc └── capture_this.cc ├── lambda_expressions_and_partial_evaluation ├── partial_evaluation.cc ├── return.cc └── stored_lambda.cc ├── lambda_expressions_in_cpp14 ├── generalized.cc ├── generalized_init_capture.cc └── generic.cc ├── lambda_expressions_introduction ├── functor.cc └── lambda.cc ├── lambda_expressions_practical ├── algo_lambda.cc └── by_hand.cc ├── less_than_operator ├── main_sort.cc ├── main_student.cc ├── sort.cc ├── student.h ├── student_by_name.cc └── student_by_number.cc ├── library_defined_operators └── compare.cc ├── library_function_objects ├── sort_greater.cc └── sort_less.cc ├── list └── list.cc ├── list_operations ├── merge.cc ├── remove.cc ├── splice.cc └── splice_forward.cc ├── local_variables ├── address.cc ├── reference.cc └── value.cc ├── loops_and_iterators ├── arr_begin_end.cc ├── new_begin_end.cc ├── range_for.cc └── reverse.cc ├── lvalues_and_rvalue_references ├── move.cc └── rvalue_reference.cc ├── lvalues_and_rvalues └── const_ref.cc ├── map ├── add_remove.cc ├── algos.cc ├── find_count.cc └── subscript.cc ├── map_insertion └── insert.cc ├── maps_in_cpp17 ├── if_initializer.cc ├── insert.cc ├── insert_or_assign.cc ├── loop.cc └── pair.cc ├── mastermind ├── constants.h ├── input.cc ├── input.h ├── main.cc ├── validate.cc └── validate.h ├── mathematical_types ├── input_output.cc ├── literal.cc ├── nonmember.cc └── operators.cc ├── member_and_non_member ├── plus_member.cc └── plus_non_member.cc ├── member_function_inheritance ├── extend.cc ├── inherit.cc ├── protected.cc └── reimplement.cc ├── member_function_pointers ├── bind.cc ├── call.cc ├── invoke.cc └── mem_fn.cc ├── merging_algorithms ├── merge.cc ├── set_intersection.cc └── set_union.cc ├── min_and_max_algorithms ├── initializer_list.cc ├── max_and_min_element.cc ├── min_and_max_algorithms.cc ├── minmax.cc ├── minmax_element.cc └── predicate.cc ├── miscellaneous_string_operations ├── data.cc └── swap.cc ├── miscellaneous_template_features ├── default_class.cc ├── default_function.cc └── static_assert.cc ├── move_only_and_raii ├── capture.cc ├── capture_by_value.cc └── move_only.cc ├── move_operators ├── better_example.cc └── move_operators.cc ├── multiple_inheritance ├── class_scope.cc ├── hierarchy.cc └── unambiguous.cc ├── multiset_multimap ├── multimap.cc ├── multimap_find_key_value.cc ├── multimap_find_keys.cc └── multiset.cc ├── namespaces └── hiding.cc ├── nested_maps ├── list_initializer.cc ├── nested_map_erase.cc ├── nested_map_insert.cc ├── nested_map_iteration.cc └── using_statement.cc ├── noexcept_keyword ├── overload.cc └── override.cc ├── numeric_algorithms ├── accumulate.cc ├── accumulate_predicate.cc ├── iota.cc └── reduce.cc ├── numeric_types_and_literals ├── bases.cc ├── int_size.cc └── numeric.cc ├── overloading_member_functions ├── define.cc ├── hiding.cc ├── overload.cc └── using.cc ├── pImpl_idiom ├── new_delete │ ├── Client.cpp │ ├── Date.cpp │ ├── Date.h │ └── Date_impl.h └── unique_ptr │ ├── Client.cpp │ ├── Date.cpp │ ├── Date.h │ └── Date_impl.h ├── pair_type ├── find_index.cc ├── find_index_03.cc ├── find_index_17.cc └── pair.cc ├── palindrome_checker └── palindrome.cc ├── partitioning_algorithms ├── is_partitioned.cc ├── partition.cc ├── partition_point.cc └── stable_partition.cc ├── perfect_forwarding └── perfect_forward.cc ├── perfect_forwarding_practical └── make_test.cc ├── permutation_algorithms ├── is_permutation.cc ├── next_permutation.cc └── prev_permutation.cc ├── pointers_and_memory ├── array.cc ├── delete.cc ├── leak.cc └── pointer.cc ├── pointers_references_and_inheritance ├── cast.cc ├── container.cc ├── function_arg.cc ├── member_functions.cc ├── pointer.cc └── reference.cc ├── prefix_and_postfix └── complex.cc ├── printing_out_class_member_data ├── print1.cc ├── print2.cc └── print3.cc ├── priority_queue └── priority_queue.cc ├── project_breakout ├── 01_basic_window │ ├── constants.h │ └── main.cc ├── 02_random_walk │ ├── constants.h │ └── random_walk.cc ├── 03_sprite │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── constants.h │ ├── entity.h │ └── main.cc ├── 04_ball │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── constants.h │ ├── entity.h │ └── main.cc ├── 05_bouncing_ball │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ └── main.cc ├── 06_paddle │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 07_moving_paddle │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 08_ball_paddle_interaction │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 09_bricks │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── brick.cc │ ├── brick.h │ ├── brick01.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 10_brick_ball_interaction │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── brick.cc │ ├── brick.h │ ├── brick01.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 11_game_manager │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── brick.cc │ ├── brick.h │ ├── brick01.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── game.cc │ ├── game.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 12_entity_manager │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── brick.cc │ ├── brick.h │ ├── brick01.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── game.cc │ ├── game.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── 13_brick_strength │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── brick.cc │ ├── brick.h │ ├── brick01.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── game.cc │ ├── game.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png └── 14_more_features │ ├── background.cc │ ├── background.h │ ├── background.jpg │ ├── ball.cc │ ├── ball.h │ ├── ball.png │ ├── brick.cc │ ├── brick.h │ ├── brick01.png │ ├── constants.h │ ├── entity.cc │ ├── entity.h │ ├── game.cc │ ├── game.h │ ├── interactions.cc │ ├── interactions.h │ ├── main.cc │ ├── paddle.cc │ ├── paddle.h │ └── paddle.png ├── queue └── queue.cc ├── raii_class_with_move_operators ├── move_and_swap.cc ├── move_assignment.cc ├── move_constructor_1st.cc └── move_constructor_final.cc ├── random_access_to_streams └── tell_sstream.cc ├── random_number_algorithms ├── bernoulli.cc ├── shuffle.cc └── shuffle_implementation.cc ├── random_numbers_in_modern_cpp ├── distribution.cc ├── engine.cc └── random.cc ├── random_numbers_in_traditional_cpp ├── rand.cc ├── rand_range.cc └── seed.cc ├── random_walk_practical ├── constants.h ├── random_walk_1d.cc └── random_walk_2d.cc ├── reference_counting ├── string.cc └── string_move.cc ├── removing_algorithms ├── erase.cc └── remove.cc ├── removing_algorithms_continued ├── remove_copy.cc ├── remove_copy_if.cc ├── remove_if.cc ├── unique.cc ├── unique_copy.cc ├── unique_copy_pred.cc └── unique_pred.cc ├── removing_elements_strings ├── assign.cc ├── erase.cc ├── erase2.cc ├── replace.cc └── replace2.cc ├── reordering_algorithms ├── reverse.cc ├── rotate.cc └── rotate_copy.cc ├── runtime_type_information ├── dynamic_cast_ptr.cc ├── dynamic_cast_ref.cc ├── hash_code.cc ├── type_info.cc └── typeid.cc ├── search_algorithms_continued ├── all_of.cc ├── any_of.cc ├── binary_search.cc ├── includes.cc ├── mismatch.cc └── none_of.cc ├── searching_algorithms ├── adjacent_find.cc ├── find_first_of.cc ├── find_first_of_repeat.cc ├── search.cc └── search_n.cc ├── searching_multimap ├── equal_range.cc ├── equal_range_copy_if.cc ├── equal_range_find_if.cc ├── equal_range_find_if_repeated.cc ├── find_key_value.cc └── upper_and_lower_bound.cc ├── searching_strings ├── find.cc ├── find2.cc ├── rfind.cc └── vowels.cc ├── sets ├── add_remove.cc ├── algos.cc └── find_count.cc ├── shallow_and_deep_copying ├── deep_assign.cc ├── deep_copy.cc ├── shallow_assign.cc └── shallow_copy.cc ├── shared_pointer └── operations.cc ├── sorting_algorithms ├── is_sorted.cc ├── is_sorted_until.cc ├── main_sort.cc ├── main_stable.cc ├── sort_predicate.cc ├── student.cc └── student.h ├── sorting_algorithms_continued ├── nth_element.cc ├── partial_sort.cc └── partial_sort_copy.cc ├── special_member_fns_in_c++11 └── move_only.cc ├── stack └── stack.cc ├── standard_exception_hierarchy └── bounds_checking.cc ├── standard_exception_subclasses ├── nan.cc └── stream.cc ├── standard_library_array ├── array_loop.cc ├── array_usage.cc └── function_argument.cc ├── static_and_dynamic_type └── virtual.cc ├── stream_iterators ├── istream_iterator.cc ├── istream_iterator2.cc └── ostream_iterator.cc ├── stream_manipulators_formatting ├── boolalpha.cc ├── setfill.cc └── setw.cc ├── stream_memfns_and_state ├── checking.cc ├── eof.cc ├── input.txt ├── recover.cc ├── recover2.cc ├── recover3.cc └── recover4.cc ├── streams_and_buffering ├── flush.cc └── flush2.cc ├── string_literals ├── raw.cc └── string.cc ├── stringstreams ├── data.txt ├── istringstream.cc ├── ostringstream.cc └── to_string.cc ├── swap_function └── overload.cc ├── synthesized_member_fns └── default.cc ├── template_specialization ├── partial.cc ├── specialization.cc └── specialization_func.cc ├── templates_overview ├── argument_deduction_in_cpp17.cc └── func.cc ├── trad_pointers ├── array_allocation.cc ├── pass_by_address.cc └── stack.cc ├── transform_algorithms ├── equal_strings.cc ├── transform.cc ├── transform_inplace.cc └── transform_overload.cc ├── try_catch_blocks ├── catch_elsewhere.cc ├── nested.cc ├── order.cc └── order2.cc ├── tuples ├── get.cc ├── return.cc └── tie.cc ├── tuples_in_cpp17 ├── apply.cc ├── make_from_tuple.cc └── return_cpp17.cc ├── two_dimensional_arrays ├── flattened.cc └── iteration.cc ├── unbuffered_input_and_output ├── gcount.cc ├── get_put.cc ├── input.txt └── read_write.cc ├── unions ├── tagged_union.cc └── union.cc ├── unions_continued ├── variant.cc └── wrapped_tagged_union.cc ├── unique_pointer ├── argument.cc ├── example.cc ├── init.cc ├── operations.cc ├── return.cc └── return2.cc ├── unique_pointer_and_polymorphism ├── container.cc ├── container_trad.cc ├── factory.cc └── factory_traditional.cc ├── unique_pointers_and_custom_deleters ├── network_corrected.cc └── network_wrong.cc ├── unordered_associative_containers ├── bucket.cc ├── bucket_find.cc └── unordered_map.cc ├── unordered_associative_containers_continued └── sorted.cc ├── using_special_member_functions_in_cpp11 ├── copy_only.cc └── immoveable.cc ├── variadic_templates ├── recursion.cc ├── sizeof.cc └── tuple.cc ├── virtual_destructor └── destructor.cc ├── virtual_functions ├── function_arg.cc └── function_arg_extended.cc ├── virtual_functions_in_cpp11 ├── final_class.cc ├── final_member.cc └── override.cc ├── virtual_inheritance ├── non_virtual.cc └── virtual.cc ├── weak_pointer ├── alias_dangle.cc ├── alias_safe.cc ├── queue_dangle.cc └── queue_safe.cc ├── weak_ptr_and_cycle_prevention └── cycle.cc ├── write_algorithms ├── replace.cc ├── replace_copy.cc ├── replace_copy_if.cc └── replace_if.cc └── write_only_algorithms ├── fill.cc ├── fill_n.cc ├── fill_n_bug.cc ├── fill_n_no_bug.cc ├── fill_n_no_bug_inserter.cc ├── generate.cc └── generate_n.cc /README.md: -------------------------------------------------------------------------------- 1 | # Learn-Modern-Advanced-Cpp 2 | The source code for the examples in my Udemy course "Learn Advanced Modern C++" 3 | https://www.udemy.com/course/learn-intermediate-modern-c/?referralCode=EA4B379D3E56FF1BB4F1 4 | -------------------------------------------------------------------------------- /adding_elements_strings/append.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string hello {"Hello"}; 8 | 9 | hello.append(" world"s); 10 | cout << "hello = " << hello << endl; 11 | 12 | string hello2 {"Hello"s}; 13 | 14 | hello2.append("wow!!!!"s, 3, 2); 15 | cout << "hello2 = " << hello2 << endl; 16 | } 17 | -------------------------------------------------------------------------------- /adding_elements_strings/insert1.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{ "for" }; 8 | cout << "str = " << str << endl; 9 | 10 | str.insert(2, "lde"s); 11 | cout << "str = " << str << endl; 12 | 13 | string str2{ "care" }; 14 | cout << "str2 = " << str2 << endl; 15 | 16 | string str3{ "omp" }; 17 | str2.insert(1, str3); 18 | cout << "str2 = " << str2 << endl; 19 | } -------------------------------------------------------------------------------- /adding_elements_strings/insert_iterators.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{"word"}; 8 | cout << "str = " << str << endl; 9 | 10 | auto last = end(str) - 1; // Get iterator to last character 11 | 12 | // Insert 'l' before last character 13 | str.insert(last, 'l'); 14 | cout << "str = " << str << endl; 15 | 16 | string str2{"ski"}; 17 | cout << "str2 = " << str2 << endl; 18 | auto last2 = end(str2); // Get iterator to last character plus one 19 | 20 | // Insert 'l' twice, after last character 21 | str2.insert(last2, 2, 'l'); 22 | cout << "str2 = " << str2 << endl; 23 | } -------------------------------------------------------------------------------- /adding_elements_strings/insert_iterators2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{"orld"}; 8 | cout << "str = " << str << endl; 9 | 10 | auto first = begin(str); 11 | 12 | str.insert(end(str), 16, 'd'); // Add enough elements to force a reallocation 13 | 14 | first = begin(str); // Get the new value of the iterator 15 | str.insert(first, 'w'); // Use new value of iterator 16 | cout << "str = " << str << endl; 17 | } -------------------------------------------------------------------------------- /algorithms_overview/find.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string str{"Hello world"}; 9 | cout << "String: "; 10 | 11 | for (auto c : str) 12 | cout << c << ","; 13 | cout << "\n"; 14 | 15 | auto res = find(cbegin(str), cend(str), 'l'); // Search string for first occurrence of 'l' 16 | 17 | // Check if we found it 18 | if (res != cend(str)) { 19 | // Access the result 20 | cout << "Found a matching element at index: " << res - str.cbegin() << endl; 21 | } 22 | 23 | cout << "At this point in the string: "; 24 | for (auto it = res; it != str.cend(); ++it) 25 | cout << *it; 26 | cout << endl; 27 | } -------------------------------------------------------------------------------- /algorithms_with_predicates/sort.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector names = { "Dilbert", "PHB", "Dogbert", "Asok", "Ted", "Alice", "Wally" }; 10 | 11 | cout << "Vector before sort()\n"; 12 | for (auto name : names) 13 | cout << name << ", "; 14 | cout << endl << endl; 15 | 16 | sort(begin(names), end(names)); 17 | 18 | cout << "Vector after sort()\n"; 19 | for (auto name : names) 20 | cout << name << ", "; 21 | cout << endl; 22 | } -------------------------------------------------------------------------------- /assignment_operator_overview/string.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class String { 7 | string s; 8 | public: 9 | // Constructors 10 | String(): s("") {} 11 | String(const string& s): s(s) {} 12 | 13 | // Copy constructor 14 | String(const String& arg): s(arg.s) {} 15 | 16 | // Assignment Operator 17 | String& operator =(const String& arg) { 18 | s = arg.s; 19 | return *this; 20 | } 21 | 22 | void print() { cout << s << endl; } 23 | }; 24 | 25 | int main() { 26 | String w{"world"}; 27 | String bang{"bang"}; 28 | bang = w; 29 | 30 | cout << "w = "; w.print(); 31 | cout << "bang = "; bang.print(); 32 | } -------------------------------------------------------------------------------- /attributes/cpp11.cc: -------------------------------------------------------------------------------- 1 | // Function that never returns 2 | [[ noreturn ]] 3 | void server() { 4 | while (true) { 5 | // Process incoming connections 6 | } 7 | } 8 | 9 | int main() { 10 | server(); 11 | } -------------------------------------------------------------------------------- /attributes/cpp14.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // This will give a compiler warning whenever func() is called 6 | [[ deprecated ("Use the version 2.0 interface in new code") ]] 7 | void func() { cout << "I've been deprecated!\n"; } 8 | 9 | int main() { 10 | func(); // Call deprecated function 11 | } -------------------------------------------------------------------------------- /attributes/maybe_used.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | void func() { 3 | [[ maybe_unused ]] int x; // Do not warn about unused variable x 4 | } 5 | 6 | 7 | int main() { 8 | func(); 9 | } -------------------------------------------------------------------------------- /attributes/nodiscard.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | 3 | // Function whose return value should not be ignored 4 | [[nodiscard]] int func() { 5 | return 99; 6 | } 7 | 8 | int main() { 9 | func(); // Call func and ignore its returned value 10 | } -------------------------------------------------------------------------------- /attributes/nodiscard_struct.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | 3 | // Nodiscard type 4 | // All functions which return Test are nodiscard 5 | struct [[nodiscard]] Test {}; 6 | 7 | // Function whose return value should not be ignored 8 | Test func() { 9 | return Test{}; 10 | } 11 | 12 | int main() { 13 | func(); // Call func and ignore its returned value 14 | } -------------------------------------------------------------------------------- /auto_keyword/auto_func.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int func() { // Function returning reference to const int 6 | return 5; 7 | } 8 | 9 | int main() { 10 | auto x = func(); // x has type int 11 | cout << x << endl; 12 | } 13 | -------------------------------------------------------------------------------- /auto_keyword/auto_keyword.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | auto i{42}; // Type of i is deduced as int 8 | auto str1 = "Hello"; // Type of str1 is deduced as const char* 9 | auto str2 = "Hello"s; // Type of str2 is deduced as std::string 10 | 11 | cout << "i * 2 = " << i * 2 << endl; 12 | auto it = str2.begin(); 13 | cout << "First element of str2: " << *it << endl; 14 | } -------------------------------------------------------------------------------- /auto_keyword/qualifiers.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | const int& x{6}; 7 | auto y = x; 8 | ++y; 9 | 10 | cout << "x = " << x << endl; 11 | cout << "y = " << y << endl; 12 | } -------------------------------------------------------------------------------- /base_and_derived_classes/fighter_aeroplane.cc: -------------------------------------------------------------------------------- 1 | class Vehicle { // This will be the base class 2 | int max_speed; 3 | // ... Member Functions 4 | }; 5 | 6 | class Aeroplane : public Vehicle { // This will be the derived class 7 | int max_height; 8 | // ... Member Functions 9 | }; 10 | 11 | class FighterPlane : public Aeroplane { // More specialized Aeroplane 12 | // ... Member Functions 13 | }; 14 | -------------------------------------------------------------------------------- /base_and_derived_classes/hierarchy.cc: -------------------------------------------------------------------------------- 1 | class Vehicle { // This will be the base class 2 | int max_speed; 3 | // ... Member Functions 4 | }; 5 | 6 | class Aeroplane : public Vehicle { // This will be the derived class 7 | int max_height; 8 | // ... Member Functions 9 | }; -------------------------------------------------------------------------------- /basic_string_ops/substr.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{"Hello world"}; 8 | str[1] = 'a'; // Change 2nd character to 'a' 9 | 10 | string s1 = str.substr(6); // Returns "world" 11 | string s2 = str.substr(6, 2); // Returns "wo" 12 | 13 | cout << str << endl; 14 | cout << s1 << endl; 15 | cout << s2 << endl; 16 | } -------------------------------------------------------------------------------- /bind/bind.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | using namespace std::placeholders; 9 | 10 | bool match(const string& animal, const string& species) { 11 | cout << R"(1st argument is ")" << animal << R"(", 2nd argument is ")" << species << "\"" << endl; 12 | return animal == species; 13 | } 14 | 15 | int main() { 16 | auto match_cat = bind(match, _1, "cat"); // Captures "cat" as second argument 17 | 18 | if (match_cat("dog")) { // Calls match("dog", "cat"); 19 | cout << "Matched\n"; 20 | } 21 | else { 22 | cout << "Not matched\n"; 23 | } 24 | } -------------------------------------------------------------------------------- /bind/match.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | bool match(const string& animal) { 9 | cout << R"(argument is ")" << animal << R"(")" << endl; 10 | return animal == "cat"; 11 | } 12 | 13 | int main() { 14 | vector animals = {"cat", "dog", "tiger", "lion", "bear", "cat", "giraffe"}; 15 | 16 | auto n = count_if(begin(animals), end(animals), match); 17 | cout << R"(The vector contains )" << n << R"( occurrences of the word "cat")" << endl; 18 | } -------------------------------------------------------------------------------- /bind/match_error.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | bool match(const string& animal, const string& species) { 9 | cout << R"(1st argument is ")" << animal << R"(", 2nd argument is ")" << species << "\"" << endl; 10 | return animal == species; 11 | } 12 | 13 | int main() { 14 | vector animals = {"cat", "dog", "tiger", "lion", "bear", "cat", "giraffe"}; 15 | 16 | cout << "The vector contains "; 17 | cout << count_if(count_if(begin(animals), end(animals), match("cat")) << endl; // Error! 18 | cout << R"( occurrences of the word "cat")" << endl; 19 | } -------------------------------------------------------------------------------- /casting/c.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int c = 'A'; 7 | cout << c << endl; 8 | cout << (char)c << endl; 9 | } -------------------------------------------------------------------------------- /casting/const_cast.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void print(char *str) { // Doesn't mutate str, but not declared const 6 | cout << str << endl; 7 | } 8 | 9 | int main() { 10 | const char *msg = "Hello, world!"; 11 | //print(msg); // Error - invalid conversion 12 | print(const_cast(msg)); 13 | } -------------------------------------------------------------------------------- /casting/static_cast.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int c = 'A'; 7 | cout << c << endl; 8 | cout << static_cast(c) << endl; 9 | } -------------------------------------------------------------------------------- /catch_all_handlers/catch_all.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | try { 8 | throw 42; 9 | //throw "Something went wrong"; 10 | /* 11 | vector vec; 12 | cout << vec.at(2) << endl; 13 | */ 14 | } 15 | catch (...) { 16 | cout << "Caught an exception of unknown type\n"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /character_fns/isxyz.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string hello {"Hello, World!"}; 8 | 9 | for (auto c: hello) { 10 | if (isupper(c)) 11 | cout << c << " is an upper case letter\n"; 12 | if (islower(c)) 13 | cout << c << " is a lower case letter\n"; 14 | if (ispunct(c)) 15 | cout << c << " is a punctuation character\n"; 16 | if (isspace(c)) 17 | cout << "\'" << c << "\'" << " is a whitespace character\n"; 18 | } 19 | } -------------------------------------------------------------------------------- /character_fns/toupper.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Return true if input starts with 'Y' or 'y' 7 | bool yes_or_no(const string& input) { 8 | char c = input[0]; 9 | 10 | if (toupper(c) == 'Y') // Is c equal to 'Y' or 'y'? 11 | return true; 12 | return false; 13 | } 14 | 15 | int main() { 16 | string input; 17 | cout << "Do you want to enter a string which starts with Y or y?" << endl; 18 | cin >> input; 19 | 20 | if (yes_or_no(input)) 21 | cout << "Evidently you do!\n"; 22 | else 23 | cout << R"(I will take that as a "no"!)" << endl; 24 | } -------------------------------------------------------------------------------- /chrono_clocks_and_time_points/sleep.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | cout << "Waiter!" << endl; 9 | this_thread::sleep_for(2s); 10 | cout << "You called, sir?" << endl; 11 | } 12 | -------------------------------------------------------------------------------- /chrono_clocks_and_time_points/timer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std::chrono; 5 | 6 | long long fibonacci (long long n) { 7 | return (n < 2) ? n: fibonacci(n-1) + fibonacci(n-2); 8 | } 9 | 10 | int main() { 11 | auto start = steady_clock::now(); 12 | 13 | long long n = fibonacci(45); 14 | 15 | std::cout << "Fibonacci number is " << n << std::endl; 16 | 17 | auto finish = steady_clock::now(); 18 | 19 | auto elapsed = duration_cast(finish - start).count(); 20 | std::cout << "Time taken: " << elapsed << " milliseconds" << std::endl; 21 | } -------------------------------------------------------------------------------- /chrono_duration_types/conversion.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::chrono; 6 | using namespace std::literals; // For suffixes 7 | 8 | void func(seconds sec) { // Function taking chrono::seconds argument 9 | cout << sec.count() << " seconds\n"; 10 | } 11 | 12 | int main() { 13 | //seconds sec = 2; // Error - cannot convert from int 14 | seconds sec = 2s; // OK 15 | 16 | //func(2); // Error - cannot convert from int 17 | func(2s); // OK 18 | } -------------------------------------------------------------------------------- /chrono_duration_types/operations.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::chrono; 6 | using namespace std::literals; // For suffixes 7 | 8 | int main() { 9 | seconds sec; 10 | auto s1 = 2s; 11 | auto s2 = 3s; 12 | cout << "s1 = " << s1.count() << " seconds" << endl; 13 | cout << "s2 = " << s2.count() << " seconds" << endl; 14 | 15 | sec = s1 + s2; // s == 5 seconds 16 | cout << "sec = " << sec.count() << " seconds" << endl; 17 | 18 | auto msec = sec + 43ms; // ms == 5043 milliseconds 19 | cout << "msec = " << msec.count() << " milliseconds" << endl; 20 | } -------------------------------------------------------------------------------- /classes_and_templates/member_template.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // C++14 generic lambda 6 | auto lambda = [] (auto x, auto y) { return x + y; }; 7 | 8 | // Equivalent functor class with member template 9 | class functor { 10 | public: 11 | template 12 | T operator()(T x, T y) { return x + y; } // Lambda expression body 13 | }; 14 | 15 | int main() { 16 | // Create functor object, instantiate its function call operator and call it 17 | cout << "functor()(2, 5): "; 18 | cout << functor()(2, 5) << endl; 19 | cout << "lambda()(2, 5): "; 20 | cout << lambda(2, 5) << endl; 21 | } 22 | -------------------------------------------------------------------------------- /compile_time_programming_overview/macro.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define Max(x, y) ((x) > (y) ? (x) : (y)) 4 | 5 | int main() { 6 | int a{5}, b{2}; 7 | std::cout << "a = " << a << ", b = " << b << std::endl; 8 | std::cout << "Max(a, b): " << Max(a, b) << std::endl; 9 | std::cout << "a = " << a << ", b = " << b << std::endl; 10 | std::cout << "Max(a++, b): " << Max(++a, b) << std::endl; // Replaced by ((++a) > (b) ? (++a) : (b)) 11 | std::cout << "a = " << a << ", b = " << b << std::endl; // a may be incremented twice 12 | } 13 | -------------------------------------------------------------------------------- /compile_time_programming_overview/traits.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class A {}; 5 | 6 | int main() 7 | { 8 | std::cout << std::boolalpha; 9 | std::cout << "is_arithmetic: " << std::is_arithmetic::value << '\n'; // true 10 | std::cout << "is_floating_point: " << std::is_floating_point::value << '\n'; // false 11 | std::cout << "is_class: " << std::is_class::value << '\n'; // true 12 | std::cout << "is_pointer: " << std::is_pointer::value << '\n'; // false 13 | } -------------------------------------------------------------------------------- /constant_expressions/constant_expression.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int i{42}, j{99}; 7 | 8 | // NB Compile with -pedantic with g++ 9 | int arr[i+j]; // Array dimension must be a constant expression 10 | } -------------------------------------------------------------------------------- /constant_expressions/constexpr.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | constexpr int i{42}, j{99}; 7 | 8 | int arr[i+j]; // Array dimension must be a constant expression 9 | } -------------------------------------------------------------------------------- /constexpr_if/if.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | string get_string(const T& arg) { 8 | if (std::is_same_v) // Replaced by "true" if T is a string, else "false" 9 | return arg; // Error if T is a built-in type 10 | else 11 | return to_string(arg); // Error if T is std::string 12 | } 13 | 14 | int main() { 15 | int x{42}; 16 | cout << "x: " << x << endl; 17 | cout << "get_string(x): " << get_string(x) << endl; 18 | string str{"hello"}; 19 | cout << "str: " << str << endl; 20 | cout << "get_string(str): " << get_string(str) << endl; 21 | } -------------------------------------------------------------------------------- /constexpr_if/specialization.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Template function for the general case 7 | template 8 | string get_string(const T& arg) { 9 | return to_string(arg); 10 | } 11 | 12 | // Template specialization for std::string 13 | template<> 14 | string get_string(const string& arg) { 15 | return arg; 16 | } 17 | 18 | int main() { 19 | int x{42}; 20 | cout << "x: " << x << endl; 21 | cout << "get_string(x): " << get_string(x) << endl; 22 | string str{"hello"}; 23 | cout << "str: " << str << endl; 24 | cout << "get_string(str): " << get_string(str) << endl; 25 | } -------------------------------------------------------------------------------- /constexpr_if_examples/fibonacci_constexpr.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | constexpr int fibonacci() { 8 | if constexpr (N > 1) 9 | return fibonacci() + fibonacci(); 10 | return N; 11 | } 12 | 13 | int main() { 14 | constexpr int n{10}; 15 | cout << "Fibonacci number " << n << " is: " << fibonacci() << endl; 16 | } -------------------------------------------------------------------------------- /constexpr_if_examples/fibonacci_specialization.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // General case (N > 1) 6 | template 7 | int fibonacci() { 8 | return fibonacci() + fibonacci(); 9 | } 10 | 11 | // Specialization for N == 1 12 | template<> 13 | int fibonacci<1>() { 14 | return 1; 15 | } 16 | 17 | // Specialization for N == 0 18 | template<> 19 | int fibonacci<0>() { 20 | return 0; 21 | } 22 | 23 | int main() { 24 | constexpr int n{10}; 25 | cout << "Fibonacci number " << n << " is: " << fibonacci() << endl; 26 | } -------------------------------------------------------------------------------- /constructors_in_modern_cpp/default.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class refrigerator { 6 | int temperature; 7 | bool door_open; 8 | bool power_on; 9 | public: 10 | void print() { 11 | cout << "temperature = " << temperature << endl; 12 | cout << boolalpha; 13 | cout << "door_open = " << door_open << endl; 14 | cout << "power_on = " << power_on << endl; 15 | } 16 | }; 17 | 18 | int main() { 19 | refrigerator fridge; 20 | fridge.print(); 21 | } -------------------------------------------------------------------------------- /constructors_in_modern_cpp/inplace.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class refrigerator { 6 | int temperature{2}; 7 | bool door_open{false}; 8 | bool power_on{true}; 9 | public: 10 | void print() { 11 | cout << "temperature = " << temperature << endl; 12 | cout << boolalpha; 13 | cout << "door_open = " << door_open << endl; 14 | cout << "power_on = " << power_on << endl; 15 | } 16 | }; 17 | 18 | int main() { 19 | refrigerator fridge; 20 | fridge.print(); 21 | } -------------------------------------------------------------------------------- /conversion_operators/explicit_bool.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string str; 9 | public: 10 | explicit operator int() const { return i; } // Explicit conversion operator to int 11 | explicit operator bool() const { return i; } // Explicit conversion operator to bool 12 | }; 13 | 14 | int main() { 15 | Test test; 16 | // cout << test << endl; // Error: no match for operator << 17 | cout << static_cast(test) << endl; 18 | 19 | if (test) 20 | cout << "This is allowed!" << endl; 21 | } -------------------------------------------------------------------------------- /conversion_operators/explicit_constructor.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | int i; 7 | public: 8 | explicit Test(int i) : i(i) {} 9 | }; 10 | 11 | int main() { 12 | Test test = 4; 13 | } -------------------------------------------------------------------------------- /conversion_operators/explicit_conversion.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string str; 9 | public: 10 | explicit operator int() const { return i; } // Explicit conversion operator to int 11 | }; 12 | 13 | int main() { 14 | Test test; 15 | // cout << test << endl; // Error: no match for operator << 16 | cout << static_cast(test) << endl; 17 | } -------------------------------------------------------------------------------- /conversion_operators/implicit.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string str; 9 | public: 10 | operator int() const { return i; } 11 | }; 12 | 13 | int main() { 14 | Test test; 15 | int x = test + 5; 16 | cout << x << endl; 17 | } -------------------------------------------------------------------------------- /conversion_operators/implicit2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string str; 9 | public: 10 | operator int() const { return i; } 11 | }; 12 | 13 | int main() { 14 | Test test; 15 | cout << test << endl; 16 | } -------------------------------------------------------------------------------- /conversion_operators/surprise.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int i = 99; 7 | cin << i; // This compiles!? 8 | } -------------------------------------------------------------------------------- /converting_between_strings_and_numbers/stod.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string pi {"3.14159"}; 8 | 9 | cout << "pi: " << pi << endl << endl; 10 | 11 | size_t n_processed; 12 | 13 | cout << "stoi:\n"; 14 | cout << stoi(pi, &n_processed) << endl; // Displays 3 15 | cout << n_processed << " characters processed\n\n"; 16 | cout << "stod:\n"; 17 | cout << stod(pi, &n_processed) << endl; // Displays 3.14159 18 | cout << n_processed << " characters processed\n\n"; 19 | } -------------------------------------------------------------------------------- /converting_between_strings_and_numbers/to_string.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string hello { "Hello, " }; 8 | string pi { to_string(3.14159) }; 9 | hello += pi; 10 | cout << hello << endl; 11 | } 12 | -------------------------------------------------------------------------------- /conways_game_of_life_practical/ansi_escapes.h: -------------------------------------------------------------------------------- 1 | // Required to enable ANSI escape codes on Windows 2 | // Works with Windows 10 version 1511 onwards (released 2016) 3 | #pragma once 4 | 5 | void setupConsole(void); 6 | void restoreConsole(void); -------------------------------------------------------------------------------- /conways_game_of_life_practical/cell.cc: -------------------------------------------------------------------------------- 1 | #include "cell.h" 2 | 3 | // Draw the cell on the grid 4 | void cell::draw(int row, int col) const { 5 | // ANSI control command 6 | // escape[n;mH moves the cursor to row n, column m 7 | // These are 1-based, i.e. row 1 is the first row 8 | std::cout << "\x1b[" << row + 1 << ";" << col + 1 << "H"; 9 | std::cout << (alive ? live_cell : dead_cell); 10 | } 11 | -------------------------------------------------------------------------------- /conways_game_of_life_practical/cell.h: -------------------------------------------------------------------------------- 1 | #ifndef CELL_H_ 2 | #define CELL_H_ 3 | 4 | #include 5 | 6 | #include "life.h" 7 | 8 | class cell { 9 | // Cell status 10 | bool alive; 11 | public: 12 | // Constructor 13 | // Cells are empty by default 14 | cell() : alive(false) {} 15 | 16 | // Draw the cell on the grid 17 | void draw(int row, int col) const; 18 | 19 | // Bring cell to life 20 | void create() { 21 | alive = true; 22 | } 23 | 24 | // End cell's life 25 | void erase() { 26 | alive = false; 27 | } 28 | 29 | bool is_alive() const { return alive; } 30 | }; 31 | 32 | #endif //CELL_H_ 33 | -------------------------------------------------------------------------------- /conways_game_of_life_practical/life.h: -------------------------------------------------------------------------------- 1 | #ifndef LIFE_H 2 | #define LIFE_H 3 | 4 | const char live_cell{'X'}; 5 | const char dead_cell{' '}; 6 | 7 | // Standard ANSI console, with a 1-char border 8 | // Occupied rows go from 1 to 23 9 | // Occupied columns go from 1 to 79 10 | const int rowmax = 23; 11 | const int colmax = 79; 12 | 13 | // Conway's parameters 14 | const int min_neighbours = 2; 15 | const int max_neighbours = 3; 16 | const int min_parents = 3; 17 | const int max_parents = 3; 18 | 19 | #endif // LIFE_H -------------------------------------------------------------------------------- /copy_constructor_overview/string.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::literals; 6 | 7 | class String { 8 | string s; 9 | public: 10 | // Constructors 11 | String(const string& s) : s(s) {} 12 | 13 | // Copy constructor 14 | String(const String& arg) : s(arg.s) {} 15 | 16 | void print() { cout << s << endl; } 17 | }; 18 | 19 | int main() { 20 | String w { "world"s }; // Call constructor 21 | String bang { w }; // Call copy constructor 22 | String bang2 = w; // Call copy constructor 23 | 24 | cout << "w = "; w.print(); 25 | cout << "bang = "; bang.print(); 26 | cout << "bang2 = "; bang2.print(); 27 | } -------------------------------------------------------------------------------- /copy_elision/elide.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | public: 7 | Test() { cout << "Default constructor\n"; } 8 | Test(const Test& other) { cout << "Copying\n"; } // Copy constructor with side effect 9 | }; 10 | 11 | // Function returning a temporary object 12 | Test func() { 13 | return Test(); 14 | } 15 | 16 | int main() { 17 | cout << "Calling func()" << endl; 18 | Test test = func(); // How many times is "Copying" printed out? 19 | cout << "Returned from func()" << endl; 20 | } 21 | -------------------------------------------------------------------------------- /copy_elision/nvro.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | public: 7 | Test() { cout << "Default constructor\n"; } 8 | Test(const Test& other) { cout << "Copying\n"; } // Copy constructor with side effect 9 | }; 10 | 11 | // Function returning a local variable 12 | Test func() { 13 | Test test; 14 | return test; 15 | } 16 | 17 | int main() { 18 | cout << "Calling func()" << endl; 19 | Test test = func(); // How many times is "Copying" printed out? 20 | cout << "Returned from func()" << endl; 21 | } 22 | -------------------------------------------------------------------------------- /copy_elision/temp.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | public: 7 | Test() { cout << "Default constructor\n"; } 8 | Test(const Test& other) { cout << "Copying\n"; } // Copy constructor with side effect 9 | }; 10 | 11 | // Function taking an argument by value 12 | void func(Test test) { 13 | 14 | } 15 | 16 | int main() { 17 | cout << "Calling func()" << endl; 18 | func(Test()); // How many times is "Copying" printed out? 19 | cout << "Returned from func()" << endl; 20 | } 21 | -------------------------------------------------------------------------------- /copying_algorithms/copy_n.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec {3, 1, 4, 1, 5, 9}; 15 | 16 | cout << "vec: "; 17 | print(vec); 18 | 19 | // Copy first two elements from vec into vec3 20 | vector vec2; 21 | copy_n(cbegin(vec), 2, back_inserter(vec2)); 22 | 23 | cout << "vec2: "; 24 | print(vec2); 25 | 26 | // Equivalent loop 27 | vector vec3; 28 | for (int i = 0; i < 2; ++i) 29 | vec3.push_back(vec[i]); 30 | 31 | cout << "vec3: "; 32 | print(vec3); 33 | } 34 | -------------------------------------------------------------------------------- /declaration_initialization/alias.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | //typedef vector IntVec; 6 | using IntVec = vector; 7 | 8 | int main() { 9 | vector vec_of_vec; 10 | } -------------------------------------------------------------------------------- /declaration_initialization/nullptr.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int i) { 6 | cout << "func(int) called\n"; 7 | } 8 | 9 | void func(int *i) { 10 | cout << "func(int *) called\n"; 11 | } 12 | 13 | int main() { 14 | func(NULL); 15 | func(nullptr); 16 | } -------------------------------------------------------------------------------- /declaration_initialization/vector_vector.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | vector> vec_of_vec; // Instead of vector > in C++03 8 | } -------------------------------------------------------------------------------- /decltype_keyword/decltype_auto.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | const int a{99}; // The type of a is const int 7 | auto b = a; // The type of b is int 8 | decltype(auto) c = a; // The type of c is const int 9 | 10 | cout << "b = " << b << ", c = " << c << endl; 11 | ++b; 12 | //++c; // Error! 13 | cout << "b = " << b << ", c = " << c << endl; 14 | } 15 | -------------------------------------------------------------------------------- /decltype_keyword/lvalue_rvalue.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test {}; 6 | 7 | int main() { 8 | int x{42}; 9 | 10 | // decltype with lvalue variable 11 | decltype(x) y{0}; // The type of y is int 12 | 13 | // decltype with lvalue expression 14 | decltype((x)) p{x}; // The type of p is lvalue reference to int 15 | 16 | // decltype with prvalue 17 | decltype(42) z; // The type of z is int 18 | 19 | // decltype with xvalue expression 20 | decltype(Test()) t; // The type of t is Test&& 21 | } 22 | -------------------------------------------------------------------------------- /decltype_keyword/qualifiers.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | const int x{42}; 7 | auto y = x; // The type of y is int 8 | decltype(x) z{0}; // The type of z is const int 9 | 10 | cout << "y = " << y << ", z = " << z << endl; 11 | ++y; 12 | //++z; // Error! 13 | cout << "y = " << y << ", z = " << z << endl;; 14 | } 15 | -------------------------------------------------------------------------------- /default_and_delete_keywords/delete.cc: -------------------------------------------------------------------------------- 1 | class Test { 2 | public: 3 | Test(const Test&) = delete; // Deleted copy constructor 4 | Test& operator =(const Test&) = delete; // Deleted assignment operator 5 | public: 6 | Test() = default; // Synthesized default constructor 7 | }; 8 | 9 | int main() { 10 | Test t1, t2; // Use defaulted constructor 11 | Test t3(t1); // Error: use of deleted function 12 | t2 = t1; // Error: use of deleted function 13 | } 14 | -------------------------------------------------------------------------------- /default_and_delete_keywords/uncopyable.cc: -------------------------------------------------------------------------------- 1 | class Test { 2 | private: 3 | Test(const Test&); // Copy constructor is private 4 | Test& operator =(const Test&); // Assignment operator is private 5 | public: 6 | Test() {} 7 | }; 8 | 9 | int main() { 10 | Test t1, t2; // Use default constructor 11 | //Test t3(t1); // Error: copy constructor is private 12 | //t2 = t1; // Error: assignment operator is private 13 | } 14 | -------------------------------------------------------------------------------- /deque/deque.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | deque dq; // Create an empty container 8 | 9 | dq.push_back(5); 10 | dq.push_back(1); 11 | dq.push_front(3); // Add element with value 3 before the other elements 12 | dq.push_front(2); 13 | dq.push_front(4); 14 | 15 | for (auto it: dq) { 16 | cout << it << ", "; 17 | } 18 | cout << endl; 19 | } -------------------------------------------------------------------------------- /equality_and_inequality_operators/student.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "student.h" 4 | 5 | using namespace std; 6 | 7 | bool operator ==(const student& lhs, const student& rhs) { 8 | if (lhs.id == rhs.id) { 9 | return true; 10 | } 11 | return false; 12 | } 13 | bool operator !=(const student& lhs, const student& rhs) { 14 | return !(lhs == rhs); 15 | } 16 | void student::print() { 17 | cout << "Name: " << name << ", id: " << id << endl; 18 | } -------------------------------------------------------------------------------- /equality_and_inequality_operators/student.h: -------------------------------------------------------------------------------- 1 | #ifndef STUDENT_H 2 | #define STUDENT_H 3 | 4 | #include 5 | 6 | class student { 7 | std::string name; // Student's name - not necessarily unique 8 | int id; // Student's ID number - unique to each student 9 | public: 10 | student(std::string name, int id) : name(name), id(id) {} 11 | friend bool operator ==(const student& lhs, const student& rhs); 12 | friend bool operator !=(const student& lhs, const student& rhs); 13 | void print(); 14 | }; 15 | 16 | #endif // STUDENT_H -------------------------------------------------------------------------------- /exceptions_introduction/handled.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | vector vec; 8 | try { 9 | cout << vec.at(2) << endl; // Throws an exception 10 | } 11 | catch (const std::exception& e) { // Will handle all subclasses of std::exception 12 | cout << "Exception caught: " << e.what() << endl; // Print out a description of the error condition 13 | } 14 | } -------------------------------------------------------------------------------- /exceptions_introduction/unhandled.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | vector vec; 8 | //cout << vec[2] << endl; // Invalid element access - undefined behaviour 9 | cout << vec.at(2) << endl; // Invalid element access - error condition 10 | cout << "Finished!\n"; 11 | } -------------------------------------------------------------------------------- /exceptions_workshop/error_codes.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | auto at_two = vec.at(2); // Call at() and save result in std::pair 8 | if (at_two.second) // Element exists 9 | cout << at_two.first << endl; 10 | else // Error 11 | return at_two.second; 12 | 13 | // Now edit the caller to add some code to check for the error 14 | } -------------------------------------------------------------------------------- /extern_templates/extern_int.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | extern int meaning_of_life; // Declare meaning_of_life 3 | 4 | // Declare a function 5 | void func(); -------------------------------------------------------------------------------- /extern_templates/extern_int1.cc: -------------------------------------------------------------------------------- 1 | #include "extern_int.h" 2 | 3 | void func() { 4 | meaning_of_life = 42; 5 | } 6 | -------------------------------------------------------------------------------- /extern_templates/extern_int2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include "extern_int.h" 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | func(); 8 | cout << "The meaning of life is: " << meaning_of_life << endl; 9 | } 10 | -------------------------------------------------------------------------------- /extern_templates/extern_int_impls.cc: -------------------------------------------------------------------------------- 1 | #include "extern_int.h" 2 | 3 | int meaning_of_life; // Define meaning_of_life -------------------------------------------------------------------------------- /extern_templates/extern_template.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | template 5 | std::ostream& print(std::ostream& os, const T& t) { 6 | return os << t; 7 | } 8 | 9 | extern template std::ostream& print(std::ostream& os, const std::string& str); 10 | 11 | void func(const std::string& str); -------------------------------------------------------------------------------- /extern_templates/extern_template1.cc: -------------------------------------------------------------------------------- 1 | #include "extern_template.h" 2 | 3 | void func(const std::string& str) { 4 | std::cout << "func() printing " << str << ": "; 5 | print(std::cout, str); 6 | } -------------------------------------------------------------------------------- /extern_templates/extern_template2.cc: -------------------------------------------------------------------------------- 1 | #include "extern_template.h" 2 | 3 | int main() { 4 | std::string str{"Hello"}; 5 | std::cout << "main() printing " << str << ": "; 6 | print(std::cout, str); 7 | std::cout << std::endl; 8 | func(str); 9 | std::cout << std::endl; 10 | } -------------------------------------------------------------------------------- /extern_templates/extern_template_impls.cc: -------------------------------------------------------------------------------- 1 | #include "extern_template.h" 2 | 3 | // Non-extern instantiation of the template 4 | template std::ostream& print(std::ostream& os, const std::string& str); -------------------------------------------------------------------------------- /extern_templates/manual.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Template declaration only 5 | template 6 | std::ostream& print(std::ostream& os, const T& t); 7 | 8 | // Declare non-template function 9 | void func(const std::string& str); -------------------------------------------------------------------------------- /extern_templates/manual1.cc: -------------------------------------------------------------------------------- 1 | #include "manual.h" 2 | 3 | // Define the non-template function 4 | void func(const std::string& str) { 5 | std::cout << "func() printing " << str << ": "; 6 | 7 | // Call the template function 8 | // The compiler will not instantiate it here (it cannot see the definition) 9 | print(std::cout, str); 10 | } -------------------------------------------------------------------------------- /extern_templates/manual2.cc: -------------------------------------------------------------------------------- 1 | #include "manual.h" 2 | 3 | // Define the template in one source file only 4 | template 5 | std::ostream& print(std::ostream& os, const T& t) { 6 | return os << t; 7 | } 8 | 9 | // Manual instantiation of the template 10 | template std::ostream& print(std::ostream& os, const std::string& str); 11 | 12 | int main() { 13 | std::string str{"Hello"}; 14 | std::cout << "main() printing " << str << ": "; 15 | print(std::cout, str); 16 | std::cout << std::endl; 17 | func(str); 18 | std::cout << std::endl; 19 | } -------------------------------------------------------------------------------- /file_modes/append.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | ofstream ofile; 8 | ofile.open("important.txt", fstream::app); 9 | 10 | if (!ofile) { 11 | cout << "Could not open file\n"; 12 | return -1; 13 | } 14 | 15 | ofile << "some more data"; 16 | ofile.close(); 17 | } -------------------------------------------------------------------------------- /file_modes/important.txt: -------------------------------------------------------------------------------- 1 | Important data - do not remove! 2 | -------------------------------------------------------------------------------- /file_streams/read.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | ifstream ifile{"text.txt"}; // Define ifile as an ifstream variable bound to text.txt 9 | 10 | if (ifile) { 11 | string text{""}; 12 | while (ifile >> text) { // Read a word from the file 13 | cout << text << ", "; 14 | } 15 | 16 | cout << endl; 17 | ifile.close(); // Release the binding between ifile and text.txt 18 | } 19 | } -------------------------------------------------------------------------------- /file_streams/read_getline.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | ifstream ifile{"text.txt"}; // Define ifile as an ifstream variable bound to text.txt 9 | 10 | if (ifile) { 11 | string text{""}; 12 | while (getline(ifile, text)) { // Read a word from the file 13 | cout << text << endl; 14 | } 15 | 16 | ifile.close(); // Release the binding between ifile and text.txt 17 | } 18 | } -------------------------------------------------------------------------------- /file_streams/text.txt: -------------------------------------------------------------------------------- 1 | The quick brown fox jumps over the lazy dog -------------------------------------------------------------------------------- /file_streams/text_out.txt: -------------------------------------------------------------------------------- 1 | The, quick, brown, fox, jumps, over, the, lazy, dog, -------------------------------------------------------------------------------- /file_streams/write.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | ofstream ofile{"text_out.txt"}; // Define ofile as an ofstream variable bound to text_out.txt 10 | 11 | if (ofile) { 12 | vector words = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"}; 13 | for (auto word : words) 14 | ofile << word << ", "; 15 | 16 | ofile.close(); // Release the binding between ofile and text_out.txt 17 | } 18 | } -------------------------------------------------------------------------------- /floating_point_output_formats/default.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | double pi {3.141'592'653'5}; 7 | cout << pi << endl; // Displays 3.14159 8 | 9 | double c {299'792'458}; 10 | cout << c << endl; // Displays 2.99792e+008 11 | } -------------------------------------------------------------------------------- /floating_point_output_formats/fixed.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | double c {299'792'458}; 7 | cout << fixed << c << endl; // Padded - displays 299792458.000000 8 | double e {1.602e-19}; 9 | cout << fixed << e << endl; // Truncated - displays 0.000000 10 | } -------------------------------------------------------------------------------- /floating_point_output_formats/precision.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | double pi {3.141'592'653'5}; 8 | 9 | int precision{3}, default_precision{6}; 10 | 11 | cout << "Pi to " << precision << " significant figures is "; 12 | cout << setprecision(precision) << pi << endl; 13 | 14 | cout << "Pi to " << default_precision << " significant figures is "; 15 | cout << setprecision(default_precision) << pi << endl; 16 | } -------------------------------------------------------------------------------- /floating_point_output_formats/scientific.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | double pi {3.141'592'653'5}; 7 | cout << scientific << pi << endl; // Displays 3.141593e+000 8 | cout << scientific << uppercase << pi << endl; // Displays 3.141593E+000 9 | } -------------------------------------------------------------------------------- /for_each_algorithm/for_each.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // Print each character in str on a separate line 9 | string str{"A test string"}; 10 | 11 | cout << "With for_each: "; 12 | for_each(cbegin(str), cend(str), 13 | [](const char c) { cout << c << ", "; } 14 | ); 15 | 16 | // Range for loop 17 | cout << "\nWith range for loop: "; 18 | for (auto c: str) 19 | cout << c << ", "; 20 | cout << endl; 21 | } -------------------------------------------------------------------------------- /forwarding_references/nested.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int& x) { 6 | cout << "func called with argument int&" << endl; 7 | } 8 | 9 | int main() { 10 | int i{42}; 11 | //int& & ri = i; // Error 12 | 13 | using int_ref = int&; // or typedef int& int_ref; 14 | 15 | int_ref j{i}; // j is a reference to int 16 | int_ref& rj{j}; // rj is a reference to (reference to int) 17 | 18 | func(rj); 19 | } -------------------------------------------------------------------------------- /forwarding_references/template.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test {}; 6 | 7 | template 8 | void func(T&& x) { 9 | cout << "func called" << endl; 10 | } 11 | 12 | int main() { 13 | Test t; 14 | Test& rt{t}; 15 | 16 | // T is Test& and x is T&& => Test& 17 | func(t); // Compiler instantiates func(Test& x) 18 | 19 | // T is Test& and x is T&& => Test& 20 | func(rt); // Compiler instantiates func(Test& x) 21 | 22 | // T is Test and x is T&& => Test&& 23 | func(std::move(t)); // Compiler instantiates func(Test&& x) 24 | } -------------------------------------------------------------------------------- /friend_keyword/delegate.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string s{"Hello"}; 9 | public: 10 | void print() const { 11 | cout << "i = " << i << ", s = " << s << endl; 12 | } 13 | }; 14 | 15 | void print(const Test& test) { 16 | test.print(); 17 | } 18 | 19 | int main() { 20 | Test test; 21 | print(test); 22 | } -------------------------------------------------------------------------------- /friend_keyword/friend_class.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string s{"Hello"}; 9 | public: 10 | friend class Example; 11 | }; 12 | 13 | class Example { 14 | public: 15 | void print(const Test& test) { 16 | cout << "i = " << test.i << ", s = " << test.s << endl; 17 | } 18 | }; 19 | 20 | int main() { 21 | Test test; 22 | Example ex; 23 | ex.print(test); 24 | } -------------------------------------------------------------------------------- /friend_keyword/friend_function.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string s{"Hello"}; 9 | public: 10 | friend void print(const Test&); 11 | }; 12 | 13 | void print(const Test& test) { 14 | cout << "i = " << test.i << ", s = " << test.s << endl; 15 | } 16 | 17 | int main() { 18 | Test test; 19 | print(test); 20 | } -------------------------------------------------------------------------------- /function_arguments_and_move_semantics/const_lvalue.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | string m_str; 8 | public: 9 | Test(const string& str) : m_str(str) {} 10 | }; 11 | 12 | int main() { 13 | string name; 14 | Test ltest(name); // Lvalue passed - str binds to name 15 | // str is copied into m_str 16 | 17 | Test rtest(std::move(name)); // Rvalue passed - str binds to name 18 | // str is copied into m_str 19 | } -------------------------------------------------------------------------------- /function_arguments_and_move_semantics/rvalue_ref.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | string m_str; 8 | public: 9 | Test(string&& str) : m_str(std::move(str)) {} 10 | }; 11 | 12 | int main() { 13 | string name; 14 | //Test ltest(name); // Compiler error 15 | 16 | Test rtest(std::move(name)); // Rvalue passed - str binds to name 17 | // str is moved into m_str 18 | } -------------------------------------------------------------------------------- /function_arguments_and_move_semantics/value.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | string m_str; 8 | public: 9 | Test(string str) : m_str(str) {} 10 | }; 11 | 12 | int main() { 13 | string name; 14 | Test ltest(name); // Lvalue passed - name is copied into str 15 | // str is copied into m_str 16 | 17 | Test rtest(std::move(name)); // Rvalue passed - name is moved into str 18 | // str is copied into m_str 19 | } -------------------------------------------------------------------------------- /function_arguments_and_move_semantics/value_then_move.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | string m_str; 8 | public: 9 | Test(string str) : m_str(std::move(str)) {} 10 | }; 11 | 12 | int main() { 13 | string name; 14 | Test ltest(name); // Lvalue passed - name is copied into str 15 | // str is moved into m_str 16 | 17 | Test rtest(std::move(name)); // Rvalue passed - name is moved into str 18 | // str is moved into m_str 19 | } -------------------------------------------------------------------------------- /function_call_operator/functor.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class evenp { // Class with function call operator 6 | public: 7 | bool operator() (int n) { // Our function call operator 8 | return (n % 2 == 0); // Return true if exactly divisible by 2 9 | } 10 | }; 11 | 12 | int main() { 13 | evenp is_even; // Create a functor object 14 | if (is_even(6)) // Call its function call operator with argument 6 15 | cout << "6 is an even number\n"; 16 | } 17 | -------------------------------------------------------------------------------- /function_pointer/function_pointer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int x, int y) { 6 | cout << x << " + " << y << " = " << x + y << endl; 7 | } 8 | 9 | int main() { 10 | void (*func_ptr)(int, int) = &func; 11 | //auto func_ptr = func; // The & is optional 12 | 13 | (*func_ptr)(1, 2); 14 | // func_ptr(1, 2); // The * is optional 15 | } 16 | -------------------------------------------------------------------------------- /function_pointer/function_pointer_func.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int x, int y) { 6 | cout << x << " + " << y << " = " << x + y << endl; 7 | } 8 | 9 | using pfunc = void (*)(int, int); // The * is not optional! 10 | 11 | // typedef void (*)(int, int) pfunc; // Older C++ 12 | 13 | void some_func(int x, int y, pfunc func_ptr) { 14 | (*func_ptr)(x, y); 15 | //func_ptr(x, y); // The * is optional 16 | } 17 | 18 | pfunc other_func() { 19 | return &func; 20 | } 21 | 22 | int main() { 23 | auto func_ptr = other_func(); 24 | 25 | some_func(1, 2, func_ptr); 26 | } 27 | -------------------------------------------------------------------------------- /further_numeric_algorithms/adjacent_difference.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec1 {1, 3, 6, 10, 15 }; 15 | vector vec2; 16 | 17 | cout << "Source vector: "; 18 | print_vec(vec1); 19 | 20 | adjacent_difference(cbegin(vec1), cend(vec1), back_inserter(vec2)); 21 | 22 | cout << "Target vector: "; 23 | print_vec(vec2); 24 | } -------------------------------------------------------------------------------- /further_numeric_algorithms/inner_product.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec1 {1, 3, 6, 10, 15 }; 15 | vector vec2{ 1, 2, 3, 4, 5 }; 16 | 17 | cout << "vec1: "; 18 | print_vec(vec1); 19 | cout << "vec2: "; 20 | print_vec(vec2); 21 | 22 | auto result = inner_product(cbegin(vec1), cend(vec1), cbegin(vec2), 0); 23 | 24 | cout << "The inner product of vec1 and vec2 is: " << result << endl; 25 | } -------------------------------------------------------------------------------- /further_numeric_algorithms/partial_sum.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec1 {1, 2, 3, 4, 5}; 15 | vector vec2; 16 | 17 | cout << "Source vector: "; 18 | print_vec(vec1); 19 | 20 | partial_sum(cbegin(vec1), cend(vec1), back_inserter(vec2)); 21 | 22 | cout << "Target vector: "; 23 | print_vec(vec2); 24 | } -------------------------------------------------------------------------------- /further_numeric_algos_contd/inner_product_overload.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector expected{ 0.1, 0.2, 0.3, 0.4, 0.5 }; 10 | vector actual{ 0.09, 0.22, 0.27, 0.41, 0.52 }; 11 | 12 | auto max_diff = inner_product( 13 | begin(expected), end(expected), begin(actual), 0.0, 14 | [](auto a, auto b){ return max(a,b); }, // Reduce operation 15 | [](auto l, auto r) { return fabs(r-l); }); // Transform operation 16 | 17 | cout << "Max difference is: " << max_diff << endl; 18 | } -------------------------------------------------------------------------------- /if_statements_and_switch_in_cpp17/if.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec = {1, 2, 3}; 9 | 10 | // Older C++ 11 | auto iter = begin(vec); 12 | if (iter != end(vec)) { 13 | // Safe to use the iterator here 14 | cout << "First element of vec is: " << *iter << endl; 15 | } 16 | 17 | // C++17 18 | if (auto iter = begin(vec); iter != end(vec)) { 19 | // Safe to use the iterator here 20 | cout << "First element of vec is: " << *iter << endl; 21 | } 22 | } -------------------------------------------------------------------------------- /inline_namespace/inline.cc: -------------------------------------------------------------------------------- 1 | namespace A { 2 | inline namespace B { // Namespace B is "inline" to namespace A 3 | int x; // x is a symbol defined in namespace B 4 | } 5 | //x; // No need to put B:: here 6 | } 7 | 8 | int main() { 9 | A::x = 5; // To use x outside the namespaces, we can just put A:: 10 | } 11 | -------------------------------------------------------------------------------- /inline_namespace/nested.cc: -------------------------------------------------------------------------------- 1 | namespace A { 2 | namespace B { // Namespace B is "nested" inside namespace A 3 | int x; // x is a symbol defined in namespace B 4 | } 5 | //B::x; // To use x in namespace A, we must put B:: in front of it 6 | } 7 | 8 | int main() { 9 | A::B::x = 5; // To use x in the global namespace, we put A::B:: 10 | } 11 | -------------------------------------------------------------------------------- /inline_namespace/product.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace product { 5 | #include "version1.h" 6 | #include "version2.h" 7 | 8 | void test() { 9 | refrigerator fridge; 10 | fridge.print(); 11 | } 12 | } 13 | 14 | int main() { 15 | product::test(); 16 | } 17 | -------------------------------------------------------------------------------- /inline_namespace/version1.h: -------------------------------------------------------------------------------- 1 | #ifndef VERSION1_H 2 | #define VERSION1_H 3 | 4 | #include 5 | 6 | inline namespace version1 { 7 | class refrigerator { 8 | int temperature{2}; 9 | bool door_open{false}; 10 | bool power_on{true}; 11 | public: 12 | refrigerator() {} 13 | refrigerator(int temperature) : temperature(temperature) {} 14 | void print() { 15 | std::cout << "Temperature = " << temperature; 16 | std::cout << std::boolalpha; 17 | std::cout << ", door_open = " << door_open; 18 | std::cout << ", power_on = " << power_on; 19 | } 20 | }; 21 | } 22 | 23 | #endif // VERSION1_H -------------------------------------------------------------------------------- /interfaces_and_virtual_functions/abstract_base.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Shape { 8 | public: 9 | virtual void draw() const = 0; // Pure virtual function 10 | }; 11 | 12 | class Circle : public Shape { 13 | public: 14 | void draw() const override { cout << "Drawing a Circle...\n"; } 15 | }; 16 | 17 | class Triangle : public Shape { 18 | public: 19 | void draw() const override { cout << "Drawing a Triangle...\n"; } 20 | }; 21 | 22 | int main() { 23 | Shape shape; // Does not compile - cannot create variable of abstract type 24 | } -------------------------------------------------------------------------------- /interfaces_and_virtual_functions/object_slicing.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Shape { 8 | public: 9 | virtual void draw() const { cout << "Shape::draw()\n"; } // Empty virtual function 10 | }; 11 | 12 | class Circle : public Shape { 13 | public: 14 | void draw() const override { cout << "Drawing a Circle...\n"; } 15 | }; 16 | 17 | // Function taking base class by value 18 | void draw_shape(Shape s) { 19 | s.draw(); // Always calls Shape's draw() 20 | } 21 | 22 | int main() { 23 | Circle circle; 24 | draw_shape(circle); // Pass derived class object by value as a Shape 25 | } -------------------------------------------------------------------------------- /interfacing_to_c/add.cc: -------------------------------------------------------------------------------- 1 | #include "add.h" 2 | 3 | int add(int x, int y) { 4 | return x + y; 5 | } -------------------------------------------------------------------------------- /interfacing_to_c/add.h: -------------------------------------------------------------------------------- 1 | #ifndef ADD_H 2 | #define ADD_H 3 | 4 | #ifdef __cplusplus 5 | extern "C" int add(int x, int y); 6 | #else 7 | int add(int x, int y); 8 | #endif 9 | 10 | #endif //ADD_H -------------------------------------------------------------------------------- /interfacing_to_c/add_main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "add.h" 4 | 5 | int main() { 6 | printf("add(2, 3) returns %d\n", add(2, 3)); 7 | } -------------------------------------------------------------------------------- /interfacing_to_c/array.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "array.h" 3 | 4 | int array_print(int arr[], int n) { 5 | int i = 0; 6 | for (i = 0; i < n; ++i) 7 | printf("%d,", arr[i]); 8 | 9 | printf("\n"); 10 | } -------------------------------------------------------------------------------- /interfacing_to_c/array.h: -------------------------------------------------------------------------------- 1 | #ifndef ARRAY_H 2 | #define ARRAY_H 3 | 4 | int array_print(int arr[], int n); 5 | 6 | #endif //ARRAY_H -------------------------------------------------------------------------------- /interfacing_to_c/array_main.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | extern "C" { 5 | #include "array.h" 6 | } 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | vector vec {3, 1, 4, 1, 5, 9}; 12 | 13 | cout << "Vector elements: "; 14 | for (auto v : vec) 15 | cout << v << ", "; 16 | cout << endl; 17 | 18 | cout << "Calling array_print(): "; 19 | array_print(vec.data(), vec.size()); 20 | } -------------------------------------------------------------------------------- /iterator_introduction/array_it.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | const char str[] = {'H','e','l','l','o'}; 7 | const char *pEnd = str + 5; // Pointer to element after last element 8 | const char *p = str; // Start of array 9 | 10 | while (p != pEnd) { // Gone past last element? 11 | cout << *p << ", "; 12 | ++p; // Increment to move to next element 13 | } 14 | } -------------------------------------------------------------------------------- /iterator_introduction/string_it.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{"Hello"}; 8 | string::iterator it = str.begin(); // Start of string 9 | 10 | while (it != str.end()) { // Gone past last element? 11 | cout << *it << ", "; 12 | ++it; 13 | } 14 | } -------------------------------------------------------------------------------- /iterator_introduction/string_loop.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str("Hello"); 8 | 9 | for (string::iterator it = str.begin(); it != str.end(); ++it) 10 | cout << *it << ", "; 11 | } -------------------------------------------------------------------------------- /iterator_introduction/vector_it.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | vector vec{3, 1, 4, 1, 5, 9}; 8 | 9 | vector::iterator it = vec.begin(); // Start of string 10 | 11 | while (it != vec.end()) { // Gone past last element? 12 | cout << *it << ", "; 13 | ++it; 14 | } 15 | } -------------------------------------------------------------------------------- /lambda_expressions_and_capture/nocapture_lambda.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | vector words{ "a", "collection", "of", "words", "with", "varying", "lengths" }; 12 | 13 | // Find the first element with more than 5 characters 14 | auto res = find_if(cbegin(words), cend(words), 15 | [] (const string& str) { return str.size() > 5; } 16 | ); 17 | 18 | // Display it 19 | if (res != cend(words)) { 20 | cout << R"(The first word which is more than 5 letters long is ")"; 21 | cout << *res << R"(")" << endl; 22 | } 23 | } -------------------------------------------------------------------------------- /lambda_expressions_and_capture_contd/capture_star_this.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | int time{10}; // Data member 7 | public: 8 | void countdown() { // Member function which calls a lambda expression 9 | [*this] () mutable { // Capture class object by reference 10 | if (time > 0) 11 | cout << time << endl; 12 | else if (time == 0) 13 | cout << "Liftoff!" << endl; 14 | --time; 15 | }(); // Call the lambda function 16 | } 17 | }; 18 | 19 | int main() { 20 | Test test; 21 | for (int i = 0; i < 12; ++i) 22 | test.countdown(); 23 | } -------------------------------------------------------------------------------- /lambda_expressions_and_capture_contd/capture_this.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | int time{10}; // Data member 7 | public: 8 | void countdown() { // Member function which calls a lambda expression 9 | [this] () { // Capture class object by reference 10 | if (time > 0) 11 | cout << time << endl; 12 | else if (time == 0) 13 | cout << "Liftoff!" << endl; 14 | --time; 15 | }(); // Call the lambda function 16 | } 17 | }; 18 | 19 | int main() { 20 | Test test; 21 | for (int i = 0; i < 12; ++i) 22 | test.countdown(); 23 | } -------------------------------------------------------------------------------- /lambda_expressions_and_partial_evaluation/return.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Function which returns a lambda function 7 | auto greeter(const string& salutation) { 8 | return [salutation](const string& name) { return salutation + ", "s + name; }; // The lambda function 9 | } 10 | 11 | int main() { 12 | // Store the lambda function in a variable 13 | auto greet = greeter("Hello"s); 14 | 15 | // Call the lambda function 16 | cout << "Greeting: " << greet("James") << endl; 17 | cout << "Greeting: " << greet("students") << endl; 18 | } -------------------------------------------------------------------------------- /lambda_expressions_in_cpp14/generalized.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | auto add_two = [y=2] (int x) { return x + y; }; // y is local to the lambda body 7 | cout << "Calling add_two(2) gives " << add_two(2) << endl; 8 | cout << "Calling add_two(5) gives " << add_two(5) << endl; 9 | } -------------------------------------------------------------------------------- /lambda_expressions_in_cpp14/generalized_init_capture.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int z = 1; // Scope's local variable y 7 | auto add_z_plus1 = [y = z+1](int x){ return x + y; }; // Lambda body's local variable y1 8 | 9 | cout << "Calling add_z_plus1(2) gives " << add_z_plus1(2) << endl; 10 | cout << "Calling add_z_plus1(5) gives " << add_z_plus1(5) << endl; 11 | } -------------------------------------------------------------------------------- /lambda_expressions_in_cpp14/generic.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str1{"Hello, "}; 8 | string str2{"World!"}; 9 | 10 | auto func = [] (auto x, auto y) { return x + y; }; 11 | 12 | cout << "Calling func(2, 5) gives " << func(2, 5) << endl; 13 | cout << "Calling func(3.141, 4.2) gives " << func(3.141, 4.2) << endl; 14 | cout << R"(Calling func(str1, str2) gives ")" << func(str1, str2) << R"(")" << endl; 15 | } -------------------------------------------------------------------------------- /lambda_expressions_introduction/functor.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Define a functor for the predicate 8 | class is_odd { 9 | public: 10 | bool operator () (const int n) const { return (n % 2 == 1); } 11 | }; 12 | 13 | int main() { 14 | vector vec {3, 1, 4, 1, 5, 9}; 15 | 16 | // Pass a functor object 17 | auto odd_it = find_if(cbegin(vec), cend(vec), is_odd()); 18 | 19 | // odd_it will be an iterator to the first odd element (if there is one) 20 | if (odd_it != cend(vec)) 21 | cout << "First odd element is: " << *odd_it << endl; 22 | 23 | } -------------------------------------------------------------------------------- /lambda_expressions_introduction/lambda.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec {3, 1, 4, 1, 5, 9}; 9 | 10 | // Pass a lambda expression 11 | auto odd_it = find_if(cbegin(vec), cend(vec), 12 | [](int n) { return (n % 2 == 1); } 13 | ); 14 | 15 | // odd_it will be an iterator to the first odd element (if there is one) 16 | if (odd_it != cend(vec)) 17 | cout << "First odd element is: " << *odd_it << endl; 18 | 19 | } -------------------------------------------------------------------------------- /less_than_operator/sort.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector names = { "Dilbert", "PHB", "Dogbert", "Asok", "Ted", "Alice", "Wally" }; 10 | 11 | cout << "Vector before sort()\n"; 12 | for (auto name : names) 13 | cout << name << ", "; 14 | cout << endl << endl; 15 | 16 | sort(begin(names), end(names)); 17 | 18 | cout << "Vector after sort()\n"; 19 | for (auto name : names) 20 | cout << name << ", "; 21 | cout << endl; 22 | } -------------------------------------------------------------------------------- /less_than_operator/student.h: -------------------------------------------------------------------------------- 1 | #ifndef STUDENT_H 2 | #define STUDENT_H 3 | 4 | #include 5 | 6 | class student { 7 | std::string name; // Student's name - not necessarily unique 8 | int id; // Student's ID number - unique to each student 9 | public: 10 | student(std::string name, int id) : name(name), id(id) {} 11 | friend bool operator ==(const student& lhs, const student& rhs); 12 | friend bool operator !=(const student& lhs, const student& rhs); 13 | friend bool operator <(const student& lhs, const student& rhs); 14 | void print(); 15 | }; 16 | 17 | #endif // STUDENT_H -------------------------------------------------------------------------------- /less_than_operator/student_by_name.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "student.h" 5 | 6 | using namespace std; 7 | 8 | bool operator ==(const student& lhs, const student& rhs) { 9 | if (lhs.name == rhs.name) { 10 | return true; 11 | } 12 | return false; 13 | } 14 | bool operator !=(const student& lhs, const student& rhs) { 15 | return !(lhs == rhs); 16 | } 17 | 18 | bool operator <(const student& lhs, const student& rhs) { 19 | return (lhs.name < rhs.name); // Order by name (alphabetical sort) 20 | } 21 | 22 | void student::print() { 23 | cout << "Name: " << name << ", id: " << id << endl; 24 | } 25 | -------------------------------------------------------------------------------- /less_than_operator/student_by_number.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "student.h" 5 | 6 | using namespace std; 7 | 8 | bool operator ==(const student& lhs, const student& rhs) { 9 | if (lhs.id == rhs.id) { 10 | return true; 11 | } 12 | return false; 13 | } 14 | bool operator !=(const student& lhs, const student& rhs) { 15 | return !(lhs == rhs); 16 | } 17 | 18 | bool operator <(const student& lhs, const student& rhs) { 19 | return (lhs.id < rhs.id); // Order by ID (numerical sort) 20 | } 21 | 22 | void student::print() { 23 | cout << "Name: " << name << ", id: " << id << endl; 24 | } 25 | -------------------------------------------------------------------------------- /library_function_objects/sort_greater.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector names = { "Dilbert", "PHB", "Dogbert", "Asok", "Ted", "Alice", "Wally" }; 10 | 11 | cout << "Vector before sort()\n"; 12 | for (auto name : names) 13 | cout << name << ", "; 14 | cout << endl << endl; 15 | 16 | sort(begin(names), end(names), greater()); 17 | 18 | cout << "Vector after sort() with std::greater\n"; 19 | for (auto name : names) 20 | cout << name << ", "; 21 | cout << endl; 22 | } -------------------------------------------------------------------------------- /library_function_objects/sort_less.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector names ={"Dilbert", "PHB", "Dogbert", "Asok", "Ted", "Alice", "Wally"}; 10 | 11 | cout << "Vector before sort()\n"; 12 | for (auto name : names) 13 | cout << name << ", "; 14 | cout << endl << endl; 15 | 16 | sort(begin(names), end(names), less()); 17 | 18 | cout << "Vector after sort() with std::less\n"; 19 | for (auto name : names) 20 | cout << name << ", "; 21 | cout << endl; 22 | } -------------------------------------------------------------------------------- /local_variables/address.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int *y) { // y will be a pointer to the caller's variable x 6 | cout << "Address of y is " << y << endl; 7 | *y = 1; 8 | } 9 | 10 | int main() { 11 | int x = 2; 12 | cout << "Address of x is " << &x << endl; 13 | func(&x); // x will now have the value 1 14 | cout << "After calling func(), x = " << x << endl; 15 | } -------------------------------------------------------------------------------- /local_variables/reference.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int& y) { // y will be a reference to the caller's variable x 6 | cout << "Address of y is " << &y << endl; 7 | y = 1; 8 | } 9 | 10 | int main() { 11 | int x = 2; 12 | cout << "Address of x is " << &x << endl; 13 | func(x); // x will now have the value 1 14 | cout << "After calling func(), x = " << x << endl; 15 | } -------------------------------------------------------------------------------- /local_variables/value.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int func(int y) { // y will be a copy of the caller's variable x 6 | cout << "Address of y is " << &y << endl; 7 | return y; // Copy y into the function's return value 8 | } 9 | 10 | int main() { 11 | int x = 2; 12 | cout << "Address of x is " << &x << endl; 13 | int z = func(x); // z will be a copy of func's return value 14 | cout << "Address of z is " << &z << endl; 15 | cout << "After calling func(), z = " << z << endl; 16 | } -------------------------------------------------------------------------------- /loops_and_iterators/arr_begin_end.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int arr[] = {1, 2, 3, 4, 5}; 8 | 9 | cout << "Iterator: "; 10 | for (auto it = begin(arr); it != end(arr); ++it) 11 | cout << *it << ", "; 12 | 13 | cout << endl << "Const iterator: "; 14 | for (auto it = cbegin(arr); it != cend(arr); ++it) 15 | cout << *it << ", "; 16 | 17 | cout << endl << "Reverse iterator: "; 18 | for (auto it = rbegin(arr); it != rend(arr); ++it) 19 | cout << *it << ", "; 20 | 21 | cout << endl << "Const reverse iterator: "; 22 | for (auto it = crbegin(arr); it != crend(arr); ++it) 23 | cout << *it << ", "; 24 | } -------------------------------------------------------------------------------- /loops_and_iterators/new_begin_end.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{"Hello"}; 8 | 9 | cout << "Iterator: "; 10 | for (auto it = str.begin(); it != str.end(); ++it) 11 | cout << *it << ", "; 12 | 13 | cout << endl << "Const iterator: "; 14 | for (auto it = str.cbegin(); it != str.cend(); ++it) 15 | cout << *it << ", "; 16 | 17 | cout << endl << "Reverse iterator: "; 18 | for (auto it = str.rbegin(); it != str.rend(); ++it) 19 | cout << *it << ", "; 20 | 21 | cout << endl << "Const reverse iterator: "; 22 | for (auto it = str.crbegin(); it != str.crend(); ++it) 23 | cout << *it << ", "; 24 | } -------------------------------------------------------------------------------- /loops_and_iterators/range_for.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | vector vec = {1, 2, 3, 4}; 8 | 9 | cout << "Vector elements: " << endl; 10 | for (auto el : vec) 11 | cout << el << ", "; // Prints out each element of vec 12 | 13 | cout << endl << "Adding 2 to each element" << endl; 14 | for (auto& el : vec) 15 | el += 2; // Add 2 to each element of vec 16 | 17 | cout << endl << "Modified vector elements: " << endl; 18 | for (auto el : vec) 19 | cout << el << ", "; // Prints out each element of vec 20 | } -------------------------------------------------------------------------------- /loops_and_iterators/reverse.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{"Hello"}; 8 | 9 | cout << "Iterator: "; 10 | for (auto it = str.begin(); it != str.end(); ++it) 11 | cout << *it << ", "; 12 | 13 | cout << endl << "Reverse iterator: "; 14 | for (auto it = str.rbegin(); it != str.rend(); ++it) 15 | cout << *it << ", "; 16 | } -------------------------------------------------------------------------------- /lvalues_and_rvalue_references/rvalue_reference.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void func(int&& x) { // func's argument is an "rvalue reference" 6 | cout << "Called with argument: " << x << endl; 7 | } 8 | 9 | int main() { 10 | int y{2}; 11 | 12 | func(2); // 2 is an rvalue. OK 13 | //func(y); // Error: y is an lvalue 14 | } 15 | -------------------------------------------------------------------------------- /lvalues_and_rvalues/const_ref.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int get() { return 2; } // Function returning an int 6 | 7 | void func(const int& ri) { // Function taking int by const reference 8 | cout << ri << endl; 9 | } 10 | 11 | int main() { 12 | func(get()); // Return value from get() is an rvalue 13 | // The rvalue is passed by const reference 14 | } -------------------------------------------------------------------------------- /maps_in_cpp17/pair.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | pair p(1, 3.142); // std::pair 7 | 8 | auto [i, d] = p; // Variable i has type int, initial value 1 9 | // Variable d has type double, initial value 3.142 10 | cout << "i = " << i << ", d = " << d << endl; 11 | } 12 | -------------------------------------------------------------------------------- /mastermind/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | #include 5 | 6 | namespace constants { 7 | const int npegs = 4; 8 | const int nturns = 10; 9 | const int ncolours = 3; 10 | } 11 | 12 | using peg_array = std::array; 13 | using colour_array = std::array; 14 | 15 | namespace constants { 16 | const colour_array colours = {'R', 'G', 'B'}; 17 | } 18 | 19 | #endif // CONSTANTS_H 20 | -------------------------------------------------------------------------------- /mastermind/input.h: -------------------------------------------------------------------------------- 1 | #ifndef INPUT_H 2 | #define INPUT_H 3 | 4 | #include 5 | #include "constants.h" 6 | 7 | std::string normalize(const std::string& s); 8 | peg_array get_input(); 9 | 10 | #endif //INPUT_H 11 | -------------------------------------------------------------------------------- /mastermind/validate.h: -------------------------------------------------------------------------------- 1 | #ifndef VALIDATE_H 2 | #define VALIDATE_H 3 | 4 | #include "constants.h" 5 | int exact_matches(const peg_array& guess, const peg_array& solution); 6 | int loose_matches(const peg_array& guess, const peg_array& solution); 7 | 8 | #endif //VALIDATE_H 9 | -------------------------------------------------------------------------------- /mathematical_types/input_output.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::literals; 6 | 7 | int main() { 8 | complex p; 9 | complex q{3.0, 4.0}; 10 | cout << q << endl; // Displays (3.0, 4.0) 11 | 12 | cout << "Enter a complex number, e.g. (1.5, 2.7)\n"; 13 | cin >> p; 14 | cout << "Number entered is " << p << endl; 15 | cout << "Real part: " << p.real() << ", imaginary part: " << p.imag() << endl; 16 | } -------------------------------------------------------------------------------- /mathematical_types/literal.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::literals; 6 | 7 | int main() { 8 | complex p{ 1.0, 2.0 }; 9 | cout << "p = " << p << endl; 10 | 11 | auto s = 2i; // Complex number, real part 0.0, imaginary part 2.0 12 | cout << "s = " << s << endl; 13 | 14 | auto z = 3.0 + 4i; // Complex number, real part 3.0, imaginary part 4.0 15 | cout << "z = " << z << endl; 16 | 17 | p += 4i; // Increase p's imaginary part by 4.0 18 | cout << "p = " << p << endl; 19 | } -------------------------------------------------------------------------------- /mathematical_types/nonmember.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::literals; 6 | 7 | int main() { 8 | complex p{ 3.0, 4.0 }; 9 | cout << "p = " << p << endl; 10 | 11 | cout << "p's magnitude is " << abs(p) << endl; 12 | cout << "p's phase angle is " << arg(p) << endl; 13 | cout << "p's conjugate is " << conj(p) << endl; 14 | cout << "p's square is " << pow(p, 2.0) << endl; 15 | cout << "p's sine is " << sin(p) << endl; 16 | } -------------------------------------------------------------------------------- /mathematical_types/operators.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::literals; 6 | 7 | int main() { 8 | complex p{1.0, 2.0}; 9 | cout << "p = " << p << endl; 10 | 11 | complex q{3.0, 4.0}; 12 | cout << "q = " << q << endl; 13 | 14 | cout << "r = p + q" << endl; 15 | complex r = p + q; 16 | cout << "r = " << r << endl; 17 | 18 | cout << boolalpha << "p == q is " << (p == q) << endl; 19 | 20 | // ++p; 21 | p += 1; 22 | cout << "Incrementing p gives " << p << endl; 23 | } -------------------------------------------------------------------------------- /member_and_non_member/plus_non_member.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class String { 7 | string s; 8 | public: 9 | // Constructors 10 | String(const char* str) : s(str) {} 11 | String(const string& s) : s(s) {} 12 | 13 | friend String operator +(const String& arg1, const String& arg2); 14 | 15 | void print() { cout << s << endl; } 16 | }; 17 | 18 | String operator +(const String& arg1, const String& arg2) { 19 | return arg1.s + arg2.s; 20 | } 21 | 22 | int main() { 23 | String w { "world" }, bang { "!" }; 24 | String wbang = w + bang; 25 | String hi = "hello " + w; 26 | cout << "wbang: "; wbang.print(); 27 | cout << "hi: "; hi.print(); 28 | } -------------------------------------------------------------------------------- /member_function_inheritance/extend.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void start() { cout << "Engine started: "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | void start() { 12 | cout << "Carrying out checks... "; 13 | Vehicle::start(); // Call base class member function 14 | cout << "Ready for take-off!"; 15 | } 16 | }; 17 | 18 | int main() { 19 | Aeroplane plane; 20 | plane.start(); // Calls start() on an Aeroplane object. Prints out "Engine started: " 21 | cout << "\n"; 22 | } -------------------------------------------------------------------------------- /member_function_inheritance/inherit.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void start() { cout << "Engine started "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | /// void start(); Inherited from Vehicle /// 12 | }; 13 | 14 | int main() { 15 | Aeroplane plane; 16 | plane.start(); // Calls start() on an Aeroplane object. Prints out "Engine started: " 17 | cout << "\n"; 18 | } -------------------------------------------------------------------------------- /member_function_inheritance/protected.cc: -------------------------------------------------------------------------------- 1 | class Vehicle { 2 | protected: 3 | void kids_only(); // Can only be called by this class and its children 4 | 5 | }; 6 | class Aeroplane : public Vehicle { 7 | public: 8 | void do_something() { kids_only(); } // Child can call protected member function 9 | }; 10 | 11 | int main() { 12 | Vehicle vehicle; 13 | //vehicle.kids_only(); // Cannot be called by "outsider" code 14 | } -------------------------------------------------------------------------------- /member_function_inheritance/reimplement.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void start() { cout << "Engine started: "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | void start() { 12 | cout << "Carrying out checks... "; 13 | cout << "Ready for take-off!"; 14 | } 15 | }; 16 | 17 | int main() { 18 | Aeroplane plane; 19 | plane.start(); // Calls start() on an Aeroplane object. Prints out "Engine started: " 20 | cout << "\n"; 21 | } -------------------------------------------------------------------------------- /member_function_pointers/call.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Test { 6 | public: 7 | void func(int a, const string& b) { 8 | cout << "func called with arguments " << a << " and " << b << endl; 9 | } 10 | }; 11 | 12 | int main() { 13 | // Define pds as a pointer to a member function of Test 14 | void (Test::*pds) (int, const string&); // We need the extra parentheses 15 | 16 | // Make pds point to the member function 17 | pds = &Test::func; // The '&' is not optional here 18 | 19 | Test test; 20 | (test.*pds)(42, "Hello"s); 21 | 22 | Test *ptest = &test; 23 | (ptest->*pds)(42, "Hello"s); 24 | } -------------------------------------------------------------------------------- /member_function_pointers/mem_fn.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | public: 8 | void func(int a, const string& b) { 9 | cout << "func called with arguments " << a << " and " << b << endl; 10 | } 11 | }; 12 | 13 | int main() { 14 | // Define pfunc as a pointer to a member function of Test 15 | auto pfunc = &Test::func; 16 | 17 | // Generate a callable object from pds 18 | auto f = mem_fn(pfunc); 19 | 20 | // Invoke this callable object 21 | Test test; 22 | f(test, 42, "Hello"s); // Pass the "this" object as the first argument 23 | } -------------------------------------------------------------------------------- /min_and_max_algorithms/initializer_list.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | auto mx = max( {"collection", "of", "words"} ); 9 | auto mn = min( {"collection", "of", "words"} ); 10 | 11 | cout << "max returned \"" << mx << "\", min returned \"" << mn << "\"" << endl; 12 | } -------------------------------------------------------------------------------- /min_and_max_algorithms/max_and_min_element.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector words{"a", "collection", "of", "words", "with", "varying", "lengths"}; 10 | 11 | auto max_words = max_element(cbegin(words), cend(words)); 12 | cout << "Largest element is \"" << *max_words << "\"" << endl; 13 | } -------------------------------------------------------------------------------- /min_and_max_algorithms/minmax.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | auto mm = minmax( {"collection", "of", "words"} ); 9 | 10 | cout << "Smallest value is \"" << mm.first << "\", largest value is \"" << mm.second << "\"" << endl; 11 | } -------------------------------------------------------------------------------- /min_and_max_algorithms/minmax_element.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector words{"a", "collection", "of", "words", "with", "varying", "lengths"}; 10 | auto mm = minmax_element(cbegin(words), cend(words)); 11 | auto m1 = mm.first; // Get an iterator to the smallest element 12 | auto m2 = mm.second; // Get an iterator to the largest element 13 | cout << "Smallest element is \"" << *m1 << "\"" << endl; 14 | cout << "Largest element is \"" << *m2 << "\"" << endl; 15 | } -------------------------------------------------------------------------------- /min_and_max_algorithms/predicate.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string word1{"of"}, word2{"words"}; 9 | 10 | auto mx = max(word1, word2); 11 | 12 | auto mn = min(word1, word2, 13 | [](const string& lhs, const string& rhs) { return lhs.size() < rhs.size(); }); 14 | 15 | cout << "max returned \"" << mx << "\", min returned \"" << mn << "\"" << endl; 16 | } -------------------------------------------------------------------------------- /miscellaneous_string_operations/data.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void print(int *arr, size_t size) { 7 | for (int i = 0; i < size; ++i) 8 | cout << arr[i] << ", "; 9 | } 10 | 11 | int main() { 12 | std::vector numbers {1, 2, 3, 4, 5}; 13 | 14 | print(numbers.data(), numbers.size()); 15 | } 16 | -------------------------------------------------------------------------------- /miscellaneous_string_operations/swap.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string s1{"Hello"}; 8 | string s2{"Goodbye"}; 9 | 10 | cout << "s1: " << s1 << ", s2: " << s2 << endl < 2 | 3 | template 4 | class number { 5 | T value; 6 | public: 7 | number(const T& value) : value(value) {} 8 | void print() { 9 | std::cout << "value: " << value << "\n"; 10 | } 11 | }; 12 | 13 | int main() { 14 | // Instantiate number object with long double 15 | number high_precision(1.99999); 16 | 17 | // Instantiate number object with int 18 | number<> default_number(2); 19 | 20 | high_precision.print(); 21 | default_number.print(); 22 | 23 | } -------------------------------------------------------------------------------- /miscellaneous_template_features/default_function.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | void func(const T& t1, const T& t2) { 5 | std::cout << "The sum of " << t1 << " and " << t2 << " is " << (t1 + t2) << "\n"; 6 | }; 7 | 8 | int main() { 9 | long double hp1{1.99999}, hp2{3.0004}; 10 | 11 | int normal1{2}, normal2{3}; 12 | 13 | // Instantiate function with long double 14 | func(hp1, hp2); 15 | 16 | // Instantiate function with int 17 | func(normal1, normal2); 18 | 19 | } -------------------------------------------------------------------------------- /miscellaneous_template_features/static_assert.cc: -------------------------------------------------------------------------------- 1 | static_assert(sizeof(int *) == 8, "This program requires a 64-bit compiler"); 2 | -------------------------------------------------------------------------------- /move_only_and_raii/capture.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector strings(5); 9 | 10 | cout << "Capture by reference" << endl; 11 | [&strings]() { cout << "Size in lambda = " << strings.size() << endl; }(); 12 | cout << "After calling lambda, size in main = " << strings.size() << endl; 13 | 14 | cout << endl << "Capture by move" << endl; 15 | [vs = std::move(strings)] () { cout << "Size in lambda = " << vs.size() << endl; }(); 16 | cout << "After calling lambda, size in main = " << strings.size() << endl << endl; 17 | } -------------------------------------------------------------------------------- /multiple_inheritance/hierarchy.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Hardware class 6 | class HardwareDevice { 7 | // ... 8 | }; 9 | 10 | // User interaction class 11 | class TouchResponder { 12 | // ... 13 | }; 14 | 15 | // Classes which inherit from both HardwareDevice and TouchResponder 16 | class Mouse : public HardwareDevice, public TouchResponder { /*...*/ }; 17 | class Keyboard : public HardwareDevice, public TouchResponder { /*...*/ }; 18 | class TouchScreen : public HardwareDevice, public TouchResponder { /*...*/ }; 19 | 20 | int main() { 21 | Mouse mouse; 22 | } -------------------------------------------------------------------------------- /multiset_multimap/multimap.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | multimap scores; // Create an empty std::multimap 8 | scores.insert( {"Graham"s, 78} ); // Add some elements to it 9 | scores.insert( {"Grace"s, 66} ); 10 | scores.insert( {"Graham"s, 66} ); // Add duplicate elements 11 | scores.insert( {"Graham"s, 72} ); 12 | scores.insert( {"Hareesh"s, 77} ); 13 | 14 | //scores.erase("Graham"); // Erase all elements with the key "Graham" 15 | 16 | for (auto s: scores) 17 | cout << s.first << " has a score of " << s.second << endl; 18 | } -------------------------------------------------------------------------------- /multiset_multimap/multiset.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | multiset s; // Create empty std::multiset 8 | s.insert(6); // Add some elements to it 9 | s.insert(7); 10 | s.insert(4); 11 | s.insert(6); // Add duplicate elements 12 | s.insert(6); 13 | 14 | for (auto el: s) 15 | cout << el << ", "; 16 | cout << endl; 17 | } -------------------------------------------------------------------------------- /namespaces/hiding.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int x{23}; // x defined in the global namespace 6 | 7 | namespace abc { 8 | int x{47}; // x defined in the namespace abc - hides global x 9 | void func() { 10 | cout << "x = " << x << endl; // Will use abc's x -> 47 11 | cout << "::x = " << ::x << endl; // Will use global x -> 23 12 | } 13 | } 14 | 15 | int main() { 16 | abc::func(); 17 | } -------------------------------------------------------------------------------- /nested_maps/list_initializer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | map level_one_map = { 8 | { 1, "player" }, // Element with key 1 9 | { 10, "door" } // Element with key 10 10 | }; 11 | 12 | map level_two_map = { // Create another level map 13 | {5, "player"}, 14 | {10, "monster"} 15 | }; 16 | 17 | // Game map 18 | map> game_map = { 19 | {1, level_one_map}, // Element with key 1, value first level map 20 | {2, level_two_map} // Element with key 10, value second level map 21 | }; 22 | } -------------------------------------------------------------------------------- /noexcept_keyword/overload.cc: -------------------------------------------------------------------------------- 1 | void func(); 2 | void func() noexcept; 3 | -------------------------------------------------------------------------------- /noexcept_keyword/override.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Shape { 6 | public: 7 | virtual void draw() const = 0; 8 | }; 9 | 10 | class Circle : public Shape { 11 | public: 12 | void draw() const noexcept override { cout << "Drawing a circle...\n"; } 13 | }; 14 | 15 | int main() { 16 | Circle circle; 17 | Shape& shape = circle; 18 | shape.draw(); 19 | } -------------------------------------------------------------------------------- /numeric_algorithms/accumulate.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec {3, 1, 4, 1, 5, 9}; 9 | 10 | cout << "Vector: "; 11 | for (auto v : vec) 12 | cout << v << ", "; 13 | cout << endl; 14 | 15 | auto sum = accumulate(cbegin(vec), cend(vec), 0); // Returns the sum of the elements 16 | 17 | cout << "Sum calculated by algorithm: " << sum << endl; 18 | 19 | sum = 0; 20 | for (auto v : vec) 21 | sum += v; 22 | 23 | cout << "Sum calculated by loop: " << sum << endl; 24 | } -------------------------------------------------------------------------------- /numeric_algorithms/accumulate_predicate.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec {3, 1, 4, 1, 5, 9}; 9 | 10 | cout << "Vector: "; 11 | for (auto v : vec) 12 | cout << v << ", "; 13 | cout << endl; 14 | 15 | auto sum = accumulate(cbegin(vec), cend(vec), 0, 16 | [] (int sum, int n) { return (n % 2 == 1) ? sum + n : sum; } 17 | ); 18 | 19 | cout << "Sum of odd elements: " << sum << endl; 20 | } -------------------------------------------------------------------------------- /numeric_algorithms/reduce.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec {3, 1, 4, 1, 5, 9}; 9 | auto sum = reduce(begin(vec), end(vec), 0); // Sum elements of vec using initial value 0 10 | 11 | cout << "Vector elements: "; 12 | for (auto i : vec) 13 | cout << i << ", "; 14 | cout << "\nSum of elements is " << sum << endl; 15 | } -------------------------------------------------------------------------------- /numeric_types_and_literals/bases.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // Numeric literals are decimal by default 7 | int decimal = 42; // 4*10 + 2*1 = 42 8 | cout << "Decimal: " << decimal << endl; 9 | 10 | //Hexadecimal numbers have 0x or 0X in front 11 | int hexadecimal = 0x2a; // 2*16 + 10*1 = 42 12 | cout << "Hexadecimal: " << hexadecimal << endl; 13 | 14 | //Octal numbers have 0 in front 15 | int octal = 052; // 5*8 + 2*1 = 42 16 | cout << "Octal: " << octal << endl; 17 | 18 | //Binary numbers have 0b or 0B in front (C++14 onwards) 19 | int binary = 0b101010; // 1*32 + 1*8 + 1*2 = 42 20 | cout << "Binary: " << binary << endl; 21 | } -------------------------------------------------------------------------------- /numeric_types_and_literals/numeric.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | const int one_million = 1'000'000; 7 | const int one_lakh = 1'00'000; 8 | double pi = 3.141'593; 9 | 10 | cout << "One million: " << one_million << endl; 11 | cout << "One lakh: " << one_lakh << endl; 12 | cout << "pi: " << pi << endl; 13 | } -------------------------------------------------------------------------------- /overloading_member_functions/define.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void accelerate() { cout << "Increasing speed: "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | void accelerate() { Vehicle:: accelerate(); } // Call parent version of accelerate() 12 | void accelerate(int height) { 13 | cout << "Accelerating at a height of: " << height; 14 | } 15 | }; 16 | 17 | int main() { 18 | Aeroplane plane; 19 | plane.accelerate(1000); 20 | cout << endl; 21 | plane.accelerate(); 22 | cout << endl; 23 | } 24 | -------------------------------------------------------------------------------- /overloading_member_functions/hiding.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void accelerate() { cout << "Increasing speed: "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | void accelerate(int height) { 12 | cout << "Accelerating at a height of: " << height; 13 | } 14 | }; 15 | 16 | int main() { 17 | Aeroplane plane; 18 | plane.accelerate(1000); 19 | cout << endl; 20 | plane.accelerate(); // Does not compile - no matching function 21 | } 22 | -------------------------------------------------------------------------------- /overloading_member_functions/overload.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void accelerate() { cout << "Increasing speed: "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | void accelerate(int height) { 12 | cout << "Accelerating at a height of: " << height; 13 | } 14 | }; 15 | 16 | int main() { 17 | Aeroplane plane; 18 | plane.accelerate(1000); 19 | cout << endl; 20 | } 21 | -------------------------------------------------------------------------------- /overloading_member_functions/using.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Vehicle { 6 | public: 7 | void accelerate() { cout << "Increasing speed: "; } 8 | }; 9 | class Aeroplane : public Vehicle { 10 | public: 11 | using Vehicle::accelerate; 12 | void accelerate(int height) { 13 | cout << "Accelerating at a height of: " << height; 14 | } 15 | }; 16 | 17 | int main() { 18 | Aeroplane plane; 19 | plane.accelerate(1000); 20 | cout << endl; 21 | plane.accelerate(); 22 | cout << endl; 23 | } 24 | -------------------------------------------------------------------------------- /pImpl_idiom/new_delete/Client.cpp: -------------------------------------------------------------------------------- 1 | #include "Date.h" 2 | #include 3 | 4 | int main() { 5 | //Date_impl date(16, 11, 2019); 6 | Date date(16, 11, 2019); 7 | date.print(); 8 | std::cout << "\n"; 9 | date.set_day(17); 10 | date.print(); 11 | std::cout << "\n"; 12 | } -------------------------------------------------------------------------------- /pImpl_idiom/new_delete/Date.cpp: -------------------------------------------------------------------------------- 1 | #include "Date.h" 2 | #include "Date_impl.h" 3 | 4 | // Implemented using RAII 5 | Date::Date(int day, int month, int year) { 6 | pImpl = new Date_impl(day, month, year); // Allocate in constructor 7 | } 8 | 9 | Date::~Date() { 10 | delete pImpl; 11 | } 12 | 13 | void Date::set_day(int day) { 14 | pImpl->set_day(day); 15 | } 16 | 17 | void Date::print() { 18 | pImpl->print(); 19 | } 20 | -------------------------------------------------------------------------------- /pImpl_idiom/new_delete/Date.h: -------------------------------------------------------------------------------- 1 | #ifndef Date_H 2 | #define Date_H 3 | 4 | class Date_impl; 5 | 6 | class Date { 7 | Date_impl* pImpl; 8 | public: 9 | Date(int day, int month, int year); 10 | ~Date(); 11 | 12 | void set_day(int day); 13 | void print(); 14 | }; 15 | 16 | #endif //Date_H -------------------------------------------------------------------------------- /pImpl_idiom/new_delete/Date_impl.h: -------------------------------------------------------------------------------- 1 | #ifndef Date_impl_H 2 | #define Date_impl_H 3 | 4 | #include 5 | 6 | class Date_impl { 7 | int day; 8 | int month; 9 | int year; 10 | public: 11 | Date_impl(int day, int month, int year) : day(day), month(month), year(year) {} 12 | void set_day(int d) { day = d; } 13 | void print() { std::cout << day << "/" << month << "/" << year; } 14 | }; 15 | 16 | #endif //Date_impl_H -------------------------------------------------------------------------------- /pImpl_idiom/unique_ptr/Client.cpp: -------------------------------------------------------------------------------- 1 | #include "Date.h" 2 | #include 3 | 4 | int main() { 5 | //Date_impl date(16, 11, 2019); 6 | Date date(16, 11, 2019); 7 | date.print(); 8 | std::cout << "\n"; 9 | date.set_day(17); 10 | date.print(); 11 | std::cout << "\n"; 12 | } -------------------------------------------------------------------------------- /pImpl_idiom/unique_ptr/Date.cpp: -------------------------------------------------------------------------------- 1 | #include "Date.h" 2 | #include "Date_impl.h" 3 | 4 | // Implemented using RAII 5 | Date::Date(int day, int month, int year) { 6 | pImpl = std::make_unique(day, month, year); // Allocate in constructor 7 | } 8 | 9 | Date::~Date() = default; 10 | Date::Date(Date&&) noexcept = default; 11 | Date& Date::operator=(Date&&) noexcept = default; 12 | 13 | void Date::set_day(int day) { 14 | pImpl->set_day(day); 15 | } 16 | 17 | void Date::print() { 18 | pImpl->print(); 19 | } 20 | -------------------------------------------------------------------------------- /pImpl_idiom/unique_ptr/Date.h: -------------------------------------------------------------------------------- 1 | #ifndef Date_H 2 | #define Date_H 3 | 4 | #include 5 | 6 | class Date_impl; 7 | 8 | class Date { 9 | std::unique_ptr pImpl; 10 | public: 11 | Date(int day, int month, int year); 12 | ~Date(); 13 | Date(Date&&) noexcept; 14 | Date& operator=(Date&&) noexcept; 15 | void set_day(int day); 16 | void print(); 17 | }; 18 | 19 | #endif //Date_H 20 | -------------------------------------------------------------------------------- /pImpl_idiom/unique_ptr/Date_impl.h: -------------------------------------------------------------------------------- 1 | #ifndef Date_impl_H 2 | #define Date_impl_H 3 | 4 | #include 5 | 6 | class Date_impl { 7 | int day; 8 | int month; 9 | int year; 10 | public: 11 | Date_impl(int day, int month, int year) : day(day), month(month), year(year) {} 12 | void set_day(int d) { day = d; } 13 | void print() { std::cout << day << "/" << month << "/" << year; } 14 | }; 15 | 16 | #endif //Date_impl_H -------------------------------------------------------------------------------- /pair_type/pair.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | pair wordpair{"hello", "there"}; 8 | // auto wordpair { make_pair("hello", "there") }; 9 | // pair wordpair{"hello"s, "there"s}; // C++17 CTAD 10 | 11 | 12 | cout << "First element of pair is \"" << wordpair.first << "\"" << endl; 13 | cout << "Second element of pair is \"" << wordpair.second << "\"" << endl; 14 | } -------------------------------------------------------------------------------- /partitioning_algorithms/partition.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec{3, 1, 4, 1, 5, 9, 2, 8, 6}; 15 | 16 | cout << "vec: "; 17 | print_vec(vec); 18 | 19 | // Partition by oddness: move all odd elements to the front 20 | partition(begin(vec), end(vec), [](int n) {return n % 2 == 1;}); 21 | 22 | cout << "vec after partition(): "; 23 | print_vec(vec); 24 | } -------------------------------------------------------------------------------- /partitioning_algorithms/stable_partition.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec{3, 1, 4, 1, 5, 9, 2, 8, 6}; 15 | 16 | cout << "vec: "; 17 | print_vec(vec); 18 | 19 | // Partition: move odd elements to the front of the vector 20 | stable_partition(begin(vec), end(vec), [](int n) {return n % 2 == 1;}); 21 | 22 | cout << "vec after stable_partition(): "; 23 | print_vec(vec); 24 | } -------------------------------------------------------------------------------- /permutation_algorithms/next_permutation.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string str{"abc"}; 9 | 10 | cout << "The permutations of " << str << " are: " << endl; 11 | 12 | // Loop to print out all the permutations of str, in order 13 | do { 14 | cout << str << endl; 15 | } while (next_permutation(begin(str), end(str))); 16 | } -------------------------------------------------------------------------------- /permutation_algorithms/prev_permutation.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string str{"abc"}; 9 | 10 | cout << "The permutations of " << str << " in reverse order are: " << endl; 11 | 12 | sort(begin(str), end(str), [](int m, int n) { return m > n; }); 13 | 14 | // Loop to print out all the permutations of str, in reverse order 15 | do { 16 | cout << str << endl; 17 | } while (prev_permutation(begin(str), end(str))); 18 | } -------------------------------------------------------------------------------- /pointers_and_memory/array.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | cout << "Allocating array for array\n"; 7 | int *pa = new int[20]; 8 | 9 | cout << "Populating array\n"; 10 | for (int i = 0; i < 20; ++i) { 11 | pa[i] = i; 12 | } 13 | 14 | cout << "Array elements:\n"; 15 | for (int i = 0; i < 20; ++i) { 16 | cout << pa[i] << ", "; 17 | } 18 | 19 | cout << endl; 20 | 21 | cout << "Releasing array's memory\n"; 22 | delete[] pa; 23 | 24 | cout << "Finished!\n"; 25 | } -------------------------------------------------------------------------------- /pointers_and_memory/pointer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int i{1}; // i is a stack variable 7 | int *p1 = &i; // p1 is a pointer to int. Its value is the address of i 8 | cout << "p1 = " << p1 << endl; // Displays the address of i 9 | cout << "*p1 = " << *p1 << endl; // Displays the value of i 10 | 11 | int *p2 = new int; // p2 points to memory allocated from the heap 12 | int *p3 = new int{36}; // p3 points to int with initial value 36 (C++11) 13 | //int *p3 = new int(36); // older versions of C++ 14 | } -------------------------------------------------------------------------------- /pointers_references_and_inheritance/pointer.cc: -------------------------------------------------------------------------------- 1 | class Shape {}; 2 | 3 | class Circle : public Shape {}; 4 | 5 | int main() { 6 | Circle circle; // Derived class object 7 | Shape* pshape = &circle; // Pointer to base class, points to a Circle object 8 | 9 | Shape shape; // Base class object 10 | Circle* pcircle = &shape; // Error! 11 | } 12 | -------------------------------------------------------------------------------- /pointers_references_and_inheritance/reference.cc: -------------------------------------------------------------------------------- 1 | class Shape {}; 2 | 3 | class Circle : public Shape {}; 4 | 5 | int main() { 6 | Circle circle; // Derived class object 7 | Shape& sref = circle; // Binds reference to base class, to a Circle object 8 | Shape shape; 9 | Circle& cref = shape; // Error! 10 | } 11 | -------------------------------------------------------------------------------- /printing_out_class_member_data/print1.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Test { 7 | int i{42}; 8 | string str{"Hello"s}; 9 | public: 10 | // A member function which prints out the data members of the Test class 11 | void print() const { 12 | cout << "i = " << i << ", str = " << str << endl; 13 | } 14 | }; 15 | 16 | int main() { 17 | Test test; 18 | // cout << test << endl; // Error: no match for operator << 19 | test.print(); 20 | } -------------------------------------------------------------------------------- /project_breakout/01_basic_window/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | }; 12 | 13 | #endif // CONSTANTS_H 14 | -------------------------------------------------------------------------------- /project_breakout/02_random_walk/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | struct constants { 5 | static constexpr int window_width{800}; 6 | static constexpr int window_height{600}; 7 | }; 8 | 9 | #endif // CONSTANTS_H 10 | -------------------------------------------------------------------------------- /project_breakout/03_sprite/background.cc: -------------------------------------------------------------------------------- 1 | #include "background.h" 2 | 3 | // Initialize static data 4 | sf::Texture background::texture; 5 | 6 | background::background(float x, float y) : entity() { 7 | // Load the texture 8 | texture.loadFromFile("background.jpg"); 9 | sprite.setTexture(texture); 10 | 11 | // Set the initial position and velocity of the background 12 | // Use (x, y) for the initial position of the background 13 | sprite.setPosition(x, y); 14 | } 15 | 16 | // Compute the background's new position 17 | void background::update() { 18 | // Nothing to do here 19 | } 20 | 21 | void background::draw(sf::RenderWindow& window) { 22 | // Ask the window to draw the sprite for us 23 | window.draw(sprite); 24 | } 25 | -------------------------------------------------------------------------------- /project_breakout/03_sprite/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/03_sprite/background.jpg -------------------------------------------------------------------------------- /project_breakout/03_sprite/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | }; 12 | 13 | #endif // CONSTANTS_H 14 | -------------------------------------------------------------------------------- /project_breakout/04_ball/background.cc: -------------------------------------------------------------------------------- 1 | #include "background.h" 2 | 3 | // Initialize static data 4 | sf::Texture background::texture; 5 | 6 | background::background(float x, float y) : entity() { 7 | // Load the texture 8 | texture.loadFromFile("background.jpg"); 9 | sprite.setTexture(texture); 10 | 11 | // Set the initial position and velocity of the background 12 | // Use (x, y) for the initial position of the background 13 | sprite.setPosition(x, y); 14 | } 15 | 16 | // Compute the background's new position 17 | void background::update() { 18 | // Nothing to do here 19 | } 20 | 21 | void background::draw(sf::RenderWindow& window) { 22 | // Ask the window to draw the sprite for us 23 | window.draw(sprite); 24 | } 25 | -------------------------------------------------------------------------------- /project_breakout/04_ball/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/04_ball/background.jpg -------------------------------------------------------------------------------- /project_breakout/04_ball/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/04_ball/ball.png -------------------------------------------------------------------------------- /project_breakout/04_ball/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | static constexpr float ball_speed{6.0f}; 12 | }; 13 | 14 | #endif // CONSTANTS_H 15 | -------------------------------------------------------------------------------- /project_breakout/05_bouncing_ball/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/05_bouncing_ball/background.jpg -------------------------------------------------------------------------------- /project_breakout/05_bouncing_ball/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/05_bouncing_ball/ball.png -------------------------------------------------------------------------------- /project_breakout/05_bouncing_ball/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | static constexpr float ball_speed{6.0f}; 12 | }; 13 | 14 | #endif // CONSTANTS_H 15 | -------------------------------------------------------------------------------- /project_breakout/05_bouncing_ball/entity.cc: -------------------------------------------------------------------------------- 1 | #include "entity.h" 2 | 3 | // Helper function to get the bounding box of a sprite 4 | sf::FloatRect entity::get_bounding_box() const noexcept { 5 | return sprite.getGlobalBounds(); 6 | } 7 | 8 | // Helper function to get the centre of a sprite 9 | sf::Vector2f entity::get_centre() const noexcept { 10 | auto box = get_bounding_box(); 11 | return {box.width/2.0f, box.height/2.0f}; 12 | } 13 | 14 | // Helper functions to get the position of the sprite 15 | float entity::x() const noexcept { 16 | return sprite.getPosition().x; 17 | } 18 | float entity:: y() const noexcept { 19 | return sprite.getPosition().y; 20 | } 21 | -------------------------------------------------------------------------------- /project_breakout/06_paddle/background.cc: -------------------------------------------------------------------------------- 1 | #include "background.h" 2 | 3 | // Initialize static data 4 | sf::Texture background::texture; 5 | 6 | background::background(float x, float y) : entity() { 7 | // Load the texture 8 | texture.loadFromFile("background.jpg"); 9 | sprite.setTexture(texture); 10 | 11 | // Set the initial position and velocity of the background 12 | // Use (x, y) for the initial position of the background 13 | sprite.setPosition(x, y); 14 | } 15 | 16 | // Compute the background's new position 17 | void background::update() { 18 | // Nothing to do here 19 | } 20 | 21 | void background::draw(sf::RenderWindow& window) { 22 | // Ask the window to draw the sprite for us 23 | window.draw(sprite); 24 | } 25 | -------------------------------------------------------------------------------- /project_breakout/06_paddle/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/06_paddle/background.jpg -------------------------------------------------------------------------------- /project_breakout/06_paddle/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/06_paddle/ball.png -------------------------------------------------------------------------------- /project_breakout/06_paddle/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | static constexpr float ball_speed{6.0f}; 12 | static constexpr float paddle_width{60.0f}; 13 | static constexpr float paddle_height{20.0f}; 14 | }; 15 | 16 | #endif // CONSTANTS_H 17 | -------------------------------------------------------------------------------- /project_breakout/06_paddle/entity.cc: -------------------------------------------------------------------------------- 1 | #include "entity.h" 2 | 3 | // Helper function to get the bounding box of a sprite 4 | sf::FloatRect entity::get_bounding_box() const noexcept { 5 | return sprite.getGlobalBounds(); 6 | } 7 | 8 | // Helper function to get the centre of a sprite 9 | sf::Vector2f entity::get_centre() const noexcept { 10 | auto box = get_bounding_box(); 11 | return {box.width/2.0f, box.height/2.0f}; 12 | } 13 | 14 | // Helper functions to get the position of the sprite 15 | float entity::x() const noexcept { 16 | return sprite.getPosition().x; 17 | } 18 | float entity:: y() const noexcept { 19 | return sprite.getPosition().y; 20 | } 21 | -------------------------------------------------------------------------------- /project_breakout/06_paddle/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/06_paddle/paddle.png -------------------------------------------------------------------------------- /project_breakout/07_moving_paddle/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/07_moving_paddle/background.jpg -------------------------------------------------------------------------------- /project_breakout/07_moving_paddle/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/07_moving_paddle/ball.png -------------------------------------------------------------------------------- /project_breakout/07_moving_paddle/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | static constexpr float ball_speed{6.0f}; 12 | static constexpr float paddle_width{60.0f}; 13 | static constexpr float paddle_height{20.0f}; 14 | static constexpr float paddle_speed{8.0f}; 15 | }; 16 | 17 | #endif // CONSTANTS_H 18 | -------------------------------------------------------------------------------- /project_breakout/07_moving_paddle/entity.cc: -------------------------------------------------------------------------------- 1 | #include "entity.h" 2 | 3 | // Helper function to get the bounding box of a sprite 4 | sf::FloatRect entity::get_bounding_box() const noexcept { 5 | return sprite.getGlobalBounds(); 6 | } 7 | 8 | // Helper function to get the centre of a sprite 9 | sf::Vector2f entity::get_centre() const noexcept { 10 | auto box = get_bounding_box(); 11 | return {box.width/2.0f, box.height/2.0f}; 12 | } 13 | 14 | // Helper functions to get the position of the sprite 15 | float entity::x() const noexcept { 16 | return sprite.getPosition().x; 17 | } 18 | float entity:: y() const noexcept { 19 | return sprite.getPosition().y; 20 | } 21 | -------------------------------------------------------------------------------- /project_breakout/07_moving_paddle/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/07_moving_paddle/paddle.png -------------------------------------------------------------------------------- /project_breakout/08_ball_paddle_interaction/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/08_ball_paddle_interaction/background.jpg -------------------------------------------------------------------------------- /project_breakout/08_ball_paddle_interaction/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/08_ball_paddle_interaction/ball.png -------------------------------------------------------------------------------- /project_breakout/08_ball_paddle_interaction/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | // Code for a "breakout" game 5 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 6 | // Uses the SFML graphics library 7 | 8 | struct constants { 9 | static constexpr int window_width{520}; 10 | static constexpr int window_height{450}; 11 | static constexpr float ball_speed{6.0f}; 12 | static constexpr float paddle_width{60.0f}; 13 | static constexpr float paddle_height{20.0f}; 14 | static constexpr float paddle_speed{8.0f}; 15 | }; 16 | 17 | #endif // CONSTANTS_H 18 | -------------------------------------------------------------------------------- /project_breakout/08_ball_paddle_interaction/entity.cc: -------------------------------------------------------------------------------- 1 | #include "entity.h" 2 | 3 | // Helper function to get the bounding box of a sprite 4 | sf::FloatRect entity::get_bounding_box() const noexcept { 5 | return sprite.getGlobalBounds(); 6 | } 7 | 8 | // Helper function to get the centre of a sprite 9 | sf::Vector2f entity::get_centre() const noexcept { 10 | auto box = get_bounding_box(); 11 | return {box.width/2.0f, box.height/2.0f}; 12 | } 13 | 14 | // Helper functions to get the position of the sprite 15 | float entity::x() const noexcept { 16 | return sprite.getPosition().x; 17 | } 18 | float entity:: y() const noexcept { 19 | return sprite.getPosition().y; 20 | } -------------------------------------------------------------------------------- /project_breakout/08_ball_paddle_interaction/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "paddle.h" 6 | 7 | // Determine whether two entities overlap 8 | bool is_interacting(const entity& e1, const entity& e2); 9 | 10 | // Resolve potential collision between the ball and the paddle 11 | void handle_collision(ball& b, const paddle& p); 12 | 13 | #endif //INTERACTIONS_H 14 | -------------------------------------------------------------------------------- /project_breakout/08_ball_paddle_interaction/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/08_ball_paddle_interaction/paddle.png -------------------------------------------------------------------------------- /project_breakout/09_bricks/background.cc: -------------------------------------------------------------------------------- 1 | #include "background.h" 2 | 3 | // Initialize static data 4 | sf::Texture background::texture; 5 | 6 | background::background(float x, float y) : entity() { 7 | // Load the texture 8 | texture.loadFromFile("background.jpg"); 9 | sprite.setTexture(texture); 10 | 11 | // Set the initial position and velocity of the background 12 | // Use (x, y) for the initial position of the background 13 | sprite.setPosition(x, y); 14 | } 15 | 16 | // Compute the background's new position 17 | void background::update() { 18 | // Nothing to do here 19 | } 20 | 21 | void background::draw(sf::RenderWindow& window) { 22 | // Ask the window to draw the sprite for us 23 | window.draw(sprite); 24 | } 25 | -------------------------------------------------------------------------------- /project_breakout/09_bricks/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/09_bricks/background.jpg -------------------------------------------------------------------------------- /project_breakout/09_bricks/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/09_bricks/ball.png -------------------------------------------------------------------------------- /project_breakout/09_bricks/brick01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/09_bricks/brick01.png -------------------------------------------------------------------------------- /project_breakout/09_bricks/entity.cc: -------------------------------------------------------------------------------- 1 | #include "entity.h" 2 | 3 | // Helper function to get the bounding box of a sprite 4 | sf::FloatRect entity::get_bounding_box() const noexcept { 5 | return sprite.getGlobalBounds(); 6 | } 7 | 8 | // Helper function to get the centre of a sprite 9 | sf::Vector2f entity::get_centre() const noexcept { 10 | auto box = get_bounding_box(); 11 | return {box.width/2.0f, box.height/2.0f}; 12 | } 13 | 14 | // Helper functions to get the position of the sprite 15 | float entity::x() const noexcept { 16 | return sprite.getPosition().x; 17 | } 18 | float entity:: y() const noexcept { 19 | return sprite.getPosition().y; 20 | } -------------------------------------------------------------------------------- /project_breakout/09_bricks/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "paddle.h" 6 | 7 | // Determine whether two entities overlap 8 | bool is_interacting(const entity& e1, const entity& e2); 9 | 10 | // Resolve potential collision between the ball and the paddle 11 | void handle_collision(ball& b, const paddle& p); 12 | 13 | #endif //INTERACTIONS_H 14 | -------------------------------------------------------------------------------- /project_breakout/09_bricks/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/09_bricks/paddle.png -------------------------------------------------------------------------------- /project_breakout/10_brick_ball_interaction/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/10_brick_ball_interaction/background.jpg -------------------------------------------------------------------------------- /project_breakout/10_brick_ball_interaction/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/10_brick_ball_interaction/ball.png -------------------------------------------------------------------------------- /project_breakout/10_brick_ball_interaction/brick01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/10_brick_ball_interaction/brick01.png -------------------------------------------------------------------------------- /project_breakout/10_brick_ball_interaction/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "brick.h" 6 | #include "paddle.h" 7 | 8 | // Determine whether two entities overlap 9 | bool is_interacting(const entity& e1, const entity& e2); 10 | 11 | // Resolve potential collision between the ball and the paddle 12 | void handle_collision(ball& b, const paddle& p); 13 | 14 | // Resolve potential collision between the ball and a brick 15 | void handle_collision(ball& b, brick& p); 16 | 17 | #endif //INTERACTIONS_H 18 | -------------------------------------------------------------------------------- /project_breakout/10_brick_ball_interaction/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/10_brick_ball_interaction/paddle.png -------------------------------------------------------------------------------- /project_breakout/11_game_manager/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/11_game_manager/background.jpg -------------------------------------------------------------------------------- /project_breakout/11_game_manager/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/11_game_manager/ball.png -------------------------------------------------------------------------------- /project_breakout/11_game_manager/brick01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/11_game_manager/brick01.png -------------------------------------------------------------------------------- /project_breakout/11_game_manager/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "brick.h" 6 | #include "paddle.h" 7 | 8 | // Determine whether two entities overlap 9 | bool is_interacting(const entity& e1, const entity& e2); 10 | 11 | // Resolve potential collision between the ball and the paddle 12 | void handle_collision(ball& b, const paddle& p); 13 | 14 | // Resolve potential collision between the ball and a brick 15 | void handle_collision(ball& b, brick& p); 16 | 17 | #endif //INTERACTIONS_H 18 | -------------------------------------------------------------------------------- /project_breakout/11_game_manager/main.cc: -------------------------------------------------------------------------------- 1 | // Code for a "breakout" game 2 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 3 | // Uses the SFML graphics library 4 | 5 | #include "game.h" 6 | 7 | // The main function for the program 8 | int main() { 9 | // Create an instance of the game, initialize it and run it 10 | game the_game; 11 | the_game.reset(); 12 | the_game.run(); 13 | } 14 | -------------------------------------------------------------------------------- /project_breakout/11_game_manager/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/11_game_manager/paddle.png -------------------------------------------------------------------------------- /project_breakout/12_entity_manager/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/12_entity_manager/background.jpg -------------------------------------------------------------------------------- /project_breakout/12_entity_manager/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/12_entity_manager/ball.png -------------------------------------------------------------------------------- /project_breakout/12_entity_manager/brick01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/12_entity_manager/brick01.png -------------------------------------------------------------------------------- /project_breakout/12_entity_manager/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "brick.h" 6 | #include "paddle.h" 7 | 8 | // Determine whether two entities overlap 9 | bool is_interacting(const entity& e1, const entity& e2); 10 | 11 | // Resolve potential collision between the ball and the paddle 12 | void handle_collision(ball& b, const paddle& p); 13 | 14 | // Resolve potential collision between the ball and a brick 15 | void handle_collision(ball& b, brick& p); 16 | 17 | #endif //INTERACTIONS_H 18 | -------------------------------------------------------------------------------- /project_breakout/12_entity_manager/main.cc: -------------------------------------------------------------------------------- 1 | // Code for a "breakout" game 2 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 3 | // Uses the SFML graphics library 4 | 5 | #include "game.h" 6 | 7 | // The main function for the program 8 | int main() { 9 | // Create an instance of the game, initialize it and run it 10 | game the_game; 11 | the_game.reset(); 12 | the_game.run(); 13 | } 14 | -------------------------------------------------------------------------------- /project_breakout/12_entity_manager/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/12_entity_manager/paddle.png -------------------------------------------------------------------------------- /project_breakout/13_brick_strength/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/13_brick_strength/background.jpg -------------------------------------------------------------------------------- /project_breakout/13_brick_strength/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/13_brick_strength/ball.png -------------------------------------------------------------------------------- /project_breakout/13_brick_strength/brick01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/13_brick_strength/brick01.png -------------------------------------------------------------------------------- /project_breakout/13_brick_strength/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "brick.h" 6 | #include "paddle.h" 7 | 8 | // Determine whether two entities overlap 9 | bool is_interacting(const entity& e1, const entity& e2); 10 | 11 | // Resolve potential collision between the ball and the paddle 12 | void handle_collision(ball& b, const paddle& p); 13 | 14 | // Resolve potential collision between the ball and a brick 15 | void handle_collision(ball& b, brick& p); 16 | 17 | #endif //INTERACTIONS_H 18 | -------------------------------------------------------------------------------- /project_breakout/13_brick_strength/main.cc: -------------------------------------------------------------------------------- 1 | // Code for a "breakout" game 2 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 3 | // Uses the SFML graphics library 4 | 5 | #include "game.h" 6 | 7 | // The main function for the program 8 | int main() { 9 | // Create an instance of the game, initialize it and run it 10 | game the_game; 11 | the_game.reset(); 12 | the_game.run(); 13 | } 14 | -------------------------------------------------------------------------------- /project_breakout/13_brick_strength/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/13_brick_strength/paddle.png -------------------------------------------------------------------------------- /project_breakout/14_more_features/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/14_more_features/background.jpg -------------------------------------------------------------------------------- /project_breakout/14_more_features/ball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/14_more_features/ball.png -------------------------------------------------------------------------------- /project_breakout/14_more_features/brick01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/14_more_features/brick01.png -------------------------------------------------------------------------------- /project_breakout/14_more_features/interactions.h: -------------------------------------------------------------------------------- 1 | #ifndef INTERACTIONS_H 2 | #define INTERACTIONS_H 3 | 4 | #include "ball.h" 5 | #include "brick.h" 6 | #include "paddle.h" 7 | 8 | // Determine whether two entities overlap 9 | bool is_interacting(const entity& e1, const entity& e2); 10 | 11 | // Resolve potential collision between the ball and the paddle 12 | void handle_collision(ball& b, const paddle& p); 13 | 14 | // Resolve potential collision between the ball and a brick 15 | void handle_collision(ball& b, brick& p); 16 | 17 | #endif //INTERACTIONS_H 18 | -------------------------------------------------------------------------------- /project_breakout/14_more_features/main.cc: -------------------------------------------------------------------------------- 1 | // Code for a "breakout" game 2 | // Based on a talk by Vittorio Romeo and code by "FamTrimli" 3 | // Uses the SFML graphics library 4 | 5 | #include "game.h" 6 | 7 | // The main function for the program 8 | int main() { 9 | // Create an instance of the game, initialize it and run it 10 | game the_game; 11 | the_game.reset(); 12 | the_game.run(); 13 | } 14 | -------------------------------------------------------------------------------- /project_breakout/14_more_features/paddle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JamesRaynard/Learn-Modern-Advanced-Cpp/4ed345e6f38f94a260ab5954d084c641fb26406b/project_breakout/14_more_features/paddle.png -------------------------------------------------------------------------------- /random_number_algorithms/bernoulli.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | static mt19937 mt; 8 | static bernoulli_distribution bd; 9 | 10 | if (bd(mt)) 11 | cout << "Your subjects are grateful for your wise and benevolent rule\n"; 12 | else 13 | cout << "The peasants are revolting!\n"; 14 | } -------------------------------------------------------------------------------- /random_number_algorithms/shuffle.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | vector vec {3, 1, 4, 1, 5, 9}; 10 | static mt19937 mt; 11 | 12 | cout << "Vector before shuffling\n"; 13 | for (auto v : vec) 14 | cout << v << ", "; 15 | 16 | shuffle(begin(vec), end(vec), mt); 17 | 18 | cout << "\nVector after shuffling\n"; 19 | for (auto v : vec) 20 | cout << v << ", "; 21 | cout << endl; 22 | } -------------------------------------------------------------------------------- /random_numbers_in_modern_cpp/engine.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | default_random_engine eng; // Create engine object - generates sequence 8 | 9 | cout << "Five random integers:\n"; 10 | for (int i = 0; i < 5; ++i ) { 11 | cout << eng() << ", "; // Call the functor to get the next number 12 | } 13 | cout << endl; 14 | } -------------------------------------------------------------------------------- /random_numbers_in_traditional_cpp/rand.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | // Print out a pseudo-random integer 8 | cout << "Printing out a random number... "; 9 | cout << rand() << endl; 10 | } -------------------------------------------------------------------------------- /random_numbers_in_traditional_cpp/rand_range.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | // Print out a pseudo-random floating-point number with value between 0 and 1 8 | cout << 1.0*rand()/RAND_MAX << endl; // Convert the result to double! 9 | 10 | // Print out ten pseudo-random integers with value between 1 and 100 11 | for (int i = 0; i < 10; ++i) 12 | cout << (99*rand()/RAND_MAX + 1) << endl; 13 | } -------------------------------------------------------------------------------- /random_numbers_in_traditional_cpp/seed.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | srand(time(0)); // Use current time as seed 9 | 10 | // Print out a pseudo-random floating-point number with value between 0 and 1 11 | cout << 1.0*rand()/RAND_MAX << endl; // Convert the result to double! 12 | 13 | // Print out ten pseudo-random integers with value between 1 and 100 14 | for (int i = 0; i < 10; ++i) 15 | cout << (99*rand()/RAND_MAX + 1) << endl; 16 | } -------------------------------------------------------------------------------- /random_walk_practical/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSTANTS_H 2 | #define CONSTANTS_H 3 | 4 | struct constants { 5 | static constexpr int window_width{800}; 6 | static constexpr int window_height{600}; 7 | }; 8 | 9 | #endif // CONSTANTS_H 10 | -------------------------------------------------------------------------------- /removing_algorithms/remove.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec{3, 1, 4, 1, 5, 9}; 9 | 10 | cout << "original vector: "; 11 | for (auto v : vec) 12 | cout << v << ", "; 13 | cout << endl; 14 | cout << "Before calling remove, the vector has " << vec.size() << " elements\n"; 15 | 16 | auto defunct = remove(begin(vec), end(vec), 1); 17 | 18 | cout << "After calling remove, the vector has " << vec.size() << " elements\n"; 19 | 20 | cout << "Result of removal: "; 21 | 22 | for (auto v : vec) 23 | cout << v << ", "; 24 | 25 | cout << endl; 26 | } -------------------------------------------------------------------------------- /removing_algorithms_continued/remove_if.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec {3, 1, 4, 1, 5, 9}; 9 | 10 | cout << "Original vector: "; 11 | for (auto v : vec) 12 | cout << v << ", "; 13 | cout << endl; 14 | 15 | auto defunct = remove_if(begin(vec), end(vec), 16 | [] (int n) { return (n % 3 == 0); } 17 | ); 18 | 19 | // Destroy the removed elements 20 | vec.erase(defunct, end(vec)); 21 | 22 | cout << "Result of calling remove_if and erase: "; 23 | for (auto v : vec) 24 | cout << v << ", "; 25 | cout << endl; 26 | } -------------------------------------------------------------------------------- /removing_elements_strings/assign.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{ "Hello" }; 8 | cout << "str = " << str << endl; 9 | 10 | str.assign("Goodbye"); 11 | 12 | cout << "str = " << str << endl; 13 | } -------------------------------------------------------------------------------- /removing_elements_strings/erase.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string hello{ "Hello" }; 8 | cout << "hello = " << hello << endl; 9 | 10 | hello.erase(3, 1); // Erase fourth character 11 | 12 | cout << "hello = " << hello << endl; 13 | 14 | auto opos = hello.find('e'); // First occurrence of 'e' 15 | 16 | if (opos != string::npos) 17 | hello.erase(opos, 2); // Erase two elements starting with the first instance of 'e' 18 | 19 | cout << "hello = " << hello << endl; 20 | } -------------------------------------------------------------------------------- /removing_elements_strings/erase2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string hello{"hello"}; 8 | 9 | auto first = begin(hello); // Get iterator to first character 10 | hello.erase(first); // Erase it 11 | cout << "hello = " << hello << endl; 12 | 13 | hello.erase(begin(hello) + 1, end(hello)-1); // Erase all characters except first and last 14 | cout << "hello = " << hello << endl; 15 | } -------------------------------------------------------------------------------- /removing_elements_strings/replace.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{ "Say Hello" }; 8 | cout << "str = " << str << endl; 9 | 10 | auto gdx = str.find('H'); 11 | str.replace(gdx, 5, "Goodbye"); 12 | 13 | cout << "str = " << str << endl; 14 | } -------------------------------------------------------------------------------- /removing_elements_strings/replace2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str{ "Say Goodbye" }; 8 | cout << "str = " << str << endl; 9 | 10 | str.replace(begin(str), begin(str)+3, "Wave"); 11 | 12 | cout << "str = " << str << endl; 13 | } -------------------------------------------------------------------------------- /runtime_type_information/dynamic_cast_ptr.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Shape { 6 | public: 7 | virtual ~Shape() {} 8 | }; 9 | 10 | class Triangle: public Shape { 11 | }; 12 | 13 | class Circle: public Shape { 14 | public: 15 | void func() { cout << "Calling Circle's func()\n"; } 16 | }; 17 | 18 | int main() { 19 | Circle circle; 20 | Triangle triangle; 21 | //Shape *pShape = &circle; 22 | Shape *pShape = ▵ 23 | 24 | Circle *pCircle = dynamic_cast(pShape); 25 | 26 | // pCircle may be a nullptr 27 | if (pCircle) { 28 | pCircle->func(); 29 | } 30 | else { 31 | cout << "Could not cast pShape to Circle*\n"; 32 | } 33 | } -------------------------------------------------------------------------------- /runtime_type_information/dynamic_cast_ref.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Shape { 6 | public: 7 | virtual ~Shape() {} 8 | }; 9 | 10 | class Triangle: public Shape { 11 | }; 12 | 13 | class Circle: public Shape { 14 | public: 15 | void func() { cout << "Calling Circle's func()\n"; } 16 | }; 17 | 18 | int main() { 19 | Circle circle; 20 | Triangle triangle; 21 | //Shape& pShape = circle; 22 | Shape& pShape = triangle; 23 | 24 | try { 25 | // Throws std::bad_cast on error 26 | Circle& pCircle = dynamic_cast(pShape); 27 | pCircle.func(); 28 | } 29 | catch (std::exception& e) { 30 | cout << "Caught exception: " << e.what() << endl; 31 | } 32 | } -------------------------------------------------------------------------------- /runtime_type_information/type_info.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Shape { 7 | public: 8 | virtual ~Shape() {} 9 | }; 10 | 11 | class Circle : public Shape {}; 12 | class Triangle : public Shape {}; 13 | 14 | int main() { 15 | Circle circle; 16 | Triangle triangle; 17 | //Shape *pShape = &circle; 18 | Shape *pShape = ▵ 19 | 20 | const type_info& tShape = typeid(*pShape); 21 | const type_info& tCircle = typeid(circle); 22 | 23 | cout << "Dynamic type of pShape is " << tShape.name() << endl; 24 | cout << "Dynamic type of circle is " << tCircle.name() << endl; 25 | } -------------------------------------------------------------------------------- /runtime_type_information/typeid.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Shape { 7 | public: 8 | virtual ~Shape() {} 9 | }; 10 | 11 | class Circle: public Shape {}; 12 | class Triangle: public Shape {}; 13 | 14 | int main() { 15 | Circle circle; 16 | Triangle triangle; 17 | Shape *pShape = &circle; 18 | //Shape *pShape = ▵ 19 | 20 | // Do *pShape and circle have the same dynamic type? 21 | if (typeid(*pShape) == typeid(circle)) 22 | cout << "pShape points to a Circle object" << endl; 23 | else 24 | cout << "pShape does not point to a Circle object" << endl; 25 | } -------------------------------------------------------------------------------- /search_algorithms_continued/any_of.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec {3, 1, 4, 1, 5, 9}; 15 | 16 | cout << "vec: "; 17 | print_vec(vec); 18 | 19 | auto is_odd = [](int n) { return n%2 == 1; }; 20 | auto is_even = [](int n) { return n%2 == 0; }; 21 | 22 | if (any_of(cbegin(vec), cend(vec), is_odd)) 23 | cout << "Some elements of vec are odd\n"; 24 | if (any_of(cbegin(vec), cend(vec), is_even)) 25 | cout << "Some elements of vec are even\n"; 26 | } 27 | -------------------------------------------------------------------------------- /search_algorithms_continued/none_of.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print_vec(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec {1, 3, 5, 7, 9}; 15 | 16 | cout << "vec: "; 17 | print_vec(vec); 18 | 19 | auto is_odd = [](int n) { return n%2 == 1; }; 20 | auto is_even = [](int n) { return n%2 == 0; }; 21 | 22 | if (none_of(cbegin(vec), cend(vec), is_odd)) 23 | cout << "No elements of vec are odd\n"; 24 | if (none_of(cbegin(vec), cend(vec), is_even)) 25 | cout << "No elements of vec are even\n"; 26 | } 27 | -------------------------------------------------------------------------------- /searching_algorithms/adjacent_find.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string str {"Hello world"}; 9 | cout << "String to search: " << str << endl; 10 | 11 | string vowels {"aeiou"}; 12 | 13 | // Returns an iterator to first element of "ll" 14 | auto pos = adjacent_find(cbegin(str), cend(str)); 15 | 16 | if (pos != cend(str)) 17 | cout << "Found adjacent elements with value " << *pos << " at index " << distance(cbegin(str), pos) < 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string str {"Hello world"}; 9 | cout << "String to search: " << str << endl; 10 | 11 | string vowels {"aeiou"}; 12 | 13 | // Returns an iterator to the first character in "vowels" 14 | auto vowel = find_first_of(cbegin(str), cend(str), cbegin(vowels), cend(vowels)); 15 | 16 | if (vowel != cend(str)) 17 | cout << "First vowel is " << *vowel << " at index " << distance(cbegin(str), vowel) << endl; 18 | } 19 | -------------------------------------------------------------------------------- /searching_algorithms/search.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | string str {"Hello world"}; 9 | cout << "String to search: " << str << endl; 10 | 11 | string sub{"wo"}; 12 | cout << "Sarching for substring : " << sub << endl; 13 | 14 | // Returns an iterator to the first element of "wo" 15 | auto pos = search(cbegin(str), cend(str), cbegin(sub), cend(sub)); 16 | 17 | if (pos != cend(str)) 18 | cout << "Found substring " << sub << ", starting at index " << distance(cbegin(str), pos) < 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec {1, 2, 2, 3, 2, 3, 3}; 9 | 10 | // Looks for a sequence of two elements with value 3 11 | // Returns an iterator to the start of the first such sequence 12 | auto pos = search_n(cbegin(vec), cend(vec), 2, 3); 13 | 14 | if (pos != cend(vec)) 15 | cout << "Found two elements with value 3, starting at index " << distance(cbegin(vec), pos) < 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str {"Hello world"}; 8 | cout << "Initial contents of str: " << str << endl; 9 | 10 | size_t pos = str.find('o'); 11 | 12 | if (pos != string::npos) { 13 | str[pos] = 'p'; 14 | } 15 | else { 16 | cout << "Could not find the search string\n"; 17 | } 18 | 19 | cout << "Final contents of str: " << str << endl; 20 | } 21 | -------------------------------------------------------------------------------- /searching_strings/rfind.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str {"Hello world"}; 8 | cout << "Initial contents of str: " << str << endl; 9 | 10 | size_t pos = str.rfind('o'); 11 | 12 | if (pos != string::npos) { 13 | str[pos] = 'p'; 14 | } 15 | else { 16 | cout << "Could not find the search string\n"; 17 | } 18 | 19 | cout << "Final contents of str: " << str << endl; 20 | } 21 | -------------------------------------------------------------------------------- /searching_strings/vowels.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | string str {"Hello world"}; 8 | cout << "String to search: " << str << endl; 9 | 10 | string vowels {"aeiou"}; 11 | cout << "First vowel is at index " << str.find_first_of(vowels) << endl; 12 | cout << "Last vowel is at index " << str.find_last_of(vowels) << endl; 13 | cout << "First non-vowel is at index " << str.find_first_not_of(vowels) << endl; 14 | cout << "Last non-vowel is at index " << str.find_last_not_of(vowels) << endl; 15 | } 16 | -------------------------------------------------------------------------------- /sorting_algorithms/is_sorted.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec{1, 4, 5, 6, 2, 7, 5}; 15 | 16 | cout << "vec: "; 17 | print(vec); 18 | 19 | cout << "vec is sorted: " << boolalpha << is_sorted(cbegin(vec), cend(vec)) << endl; 20 | 21 | cout << "Calling sort\n"; 22 | sort(begin(vec), end(vec)); 23 | 24 | cout << "vec is sorted: " << boolalpha << is_sorted(cbegin(vec), cend(vec)) << endl; 25 | } -------------------------------------------------------------------------------- /sorting_algorithms/sort_predicate.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | vector vec{3, 1, 4, 1, 5, 9}; 15 | 16 | cout << "vec: "; 17 | print(vec); 18 | 19 | sort(begin(vec), end(vec), 20 | [](int m, int n) { return m > n; } 21 | ); 22 | 23 | cout << "vec after sorting: "; 24 | print(vec); 25 | } -------------------------------------------------------------------------------- /sorting_algorithms/student.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "student.h" 5 | 6 | using namespace std; 7 | 8 | bool operator ==(const student& lhs, const student& rhs) { 9 | if (lhs.name == rhs.name) { 10 | return true; 11 | } 12 | return false; 13 | } 14 | bool operator !=(const student& lhs, const student& rhs) { 15 | return !(lhs == rhs); 16 | } 17 | 18 | bool operator <(const student& lhs, const student& rhs) { 19 | return (lhs.name < rhs.name); // Order by name (alphabetical sort) 20 | } 21 | 22 | void student::print() { 23 | cout << "Name: " << name << ", id: " << id << endl; 24 | } 25 | -------------------------------------------------------------------------------- /sorting_algorithms/student.h: -------------------------------------------------------------------------------- 1 | #ifndef STUDENT_H 2 | #define STUDENT_H 3 | 4 | #include 5 | 6 | class student { 7 | std::string name; // Student's name - not necessarily unique 8 | int id; // Student's ID number - unique to each student 9 | public: 10 | student(std::string name, int id) : name(name), id(id) {} 11 | friend bool operator ==(const student& lhs, const student& rhs); 12 | friend bool operator !=(const student& lhs, const student& rhs); 13 | friend bool operator <(const student& lhs, const student& rhs); 14 | void print(); 15 | }; 16 | 17 | #endif // STUDENT_H -------------------------------------------------------------------------------- /sorting_algorithms_continued/partial_sort.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | string keys {"qwertyuiopasdfghjkl"}; 10 | 11 | cout << "keys: " << keys << endl << endl; 12 | 13 | auto it = begin(keys); 14 | partial_sort(it, it + 5, end(keys)); 15 | 16 | cout << "First 5 characters of keys are: " << keys.substr(0, 5) << endl; 17 | cout << "Full keys string: " << keys << endl << endl; 18 | 19 | advance(it, 5); 20 | partial_sort(it, it + 5, end(keys)); 21 | cout << "The next 5 characters of keys are: " << keys.substr(5, 5) << endl; 22 | 23 | cout << "Full keys string: " << keys << endl; 24 | } -------------------------------------------------------------------------------- /sorting_algorithms_continued/partial_sort_copy.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | string keys {"qwertyuiopasdfghjkl"}; 10 | string dest(5, ' '); 11 | 12 | cout << "keys: " << keys << endl << endl; 13 | 14 | partial_sort_copy(cbegin(keys), cend(keys), begin(dest), end(dest)); 15 | 16 | cout << "First 5 characters of keys are: " << dest << endl; 17 | cout << "Full keys string: " << keys << endl << endl; 18 | } -------------------------------------------------------------------------------- /standard_exception_subclasses/nan.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | try { 8 | cout << sqrt(-1) << endl; 9 | } 10 | catch (const std::exception& e) { 11 | cout << e.what() << endl; 12 | } 13 | } -------------------------------------------------------------------------------- /standard_exception_subclasses/stream.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // For I/O exceptions 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | ifstream ifile; 9 | 10 | // Enable exceptions for ifile 11 | ifile.exceptions(std::ifstream::failbit | std::ifstream::badbit); 12 | 13 | try { 14 | // Throws an exception if text.txt cannot be opened for reading 15 | ifile.open("text.txt"); 16 | } 17 | catch (const std::exception& e) { 18 | cout << "Exception caught: " << e.what() << endl; 19 | } 20 | } -------------------------------------------------------------------------------- /standard_library_array/array_usage.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | // std::array can be list-initialized 8 | std::array arr {1, 2, 3, 4, 5}; 9 | 10 | // Elements can be accessed and assigned to using indexing 11 | cout << "arr[3] = " << arr[3] << endl; 12 | 13 | arr[2] = 6; 14 | cout << "After assignment, arr[2] = " << arr[2] << endl; 15 | } -------------------------------------------------------------------------------- /stream_iterators/istream_iterator.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // Iterator that will read ints from cin 9 | istream_iterator ii(cin); 10 | 11 | // Read an int from the stream 12 | cout << "Please enter a number: "; 13 | int x = *ii; // This will read a number from cin into the variable x 14 | cout << "You entered " << x << endl; 15 | } -------------------------------------------------------------------------------- /stream_iterators/istream_iterator2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | istream_iterator iis(cin); // Iterator to read strings 9 | istream_iterator eof; // Empty iterator 10 | 11 | vector vs; // Vector to store input 12 | 13 | while (iis != eof) { // Do we have any input to read? 14 | vs.push_back(*iis); // Yes - store it in the vector 15 | ++iis; // Move to next input 16 | } 17 | 18 | for (auto v: vs) 19 | cout << v << endl; 20 | } -------------------------------------------------------------------------------- /stream_iterators/ostream_iterator.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | // Write the numbers 0, ..., 9 to the display followed by a newline 8 | ostream_iterator oi(cout, "\n"); // Create the output stream iterator 9 | 10 | for (int i = 0; i < 10; ++i) { 11 | *oi = i; // Prints the number followed by "\n" 12 | ++oi; // Move to next element in sequence 13 | } 14 | } -------------------------------------------------------------------------------- /stream_manipulators_formatting/boolalpha.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x = 2; 7 | bool is_negative = x < 0; 8 | 9 | cout << "The value of is_negative is " << is_negative << endl; 10 | cout << "is_negative is " << boolalpha << is_negative << endl; 11 | cout << "x == 2 is " << (x == 2) << endl; // Sticky manipulator 12 | cout << "The numerical value of \"false\" is " << noboolalpha << false << endl; 13 | } -------------------------------------------------------------------------------- /stream_manipulators_formatting/setfill.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | cout << setfill('#'); 8 | cout << setw(15) << "Penguins " << 5 << "\n"; 9 | cout << setw(15) << "Polar Bears " << 2 << "\n"; 10 | cout << setfill(' '); 11 | } -------------------------------------------------------------------------------- /stream_manipulators_formatting/setw.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | cout << setw(15) << "Penguins " << 5 << "\n"; 8 | cout << setw(15) << "Polar Bears " << 2 << "\n"; 9 | } -------------------------------------------------------------------------------- /stream_memfns_and_state/checking.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x{0}; 7 | 8 | cout << "Please enter a number: "; 9 | cin >> x; 10 | 11 | if (cin.good()) // Successfully read an int 12 | cout << "You entered the number " << x << "\n"; 13 | else if (cin.fail()) // Not an int. Probably a user error - try again 14 | cout << "Please try again and enter a number\n"; 15 | else if (cin.bad()) // A serious error occurred 16 | cout << "Something has gone seriously wrong\n"; 17 | } -------------------------------------------------------------------------------- /stream_memfns_and_state/eof.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | ifstream ifile; 8 | ifile.open("input.txt"); 9 | 10 | int x{0}; 11 | 12 | // Wrong 13 | while (!ifile.eof()) { 14 | ifile >> x; 15 | cout << x << ", "; 16 | } 17 | 18 | // Correct 19 | while (ifile >> x) 20 | cout << x << ", "; 21 | cout << endl; 22 | } -------------------------------------------------------------------------------- /stream_memfns_and_state/input.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 3 5 | 4 6 | 5 7 | 6 8 | 7 9 | 8 10 | 9 11 | -------------------------------------------------------------------------------- /stream_memfns_and_state/recover.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x{0}; 7 | 8 | cout << "Please enter a number: "; 9 | cin >> x; 10 | 11 | bool success{false}; 12 | while (!success) { 13 | if (cin.good()) { 14 | cout << "You entered the number " << x << "\n"; 15 | success = true; 16 | } 17 | else if (cin.fail()) { 18 | cout << "Please try again and enter a number\n"; 19 | cin >> x; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /stream_memfns_and_state/recover2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x{0}; 7 | 8 | cout << "Please enter a number: "; 9 | cin >> x; 10 | 11 | bool success{false}; 12 | while (!success) { 13 | if (cin.good()) { 14 | cout << "You entered the number " << x << "\n"; 15 | success = true; 16 | } 17 | else if (cin.fail()) { 18 | cout << "Please try again and enter a number\n"; 19 | cin.clear(); 20 | cin >> x; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /stream_memfns_and_state/recover3.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int x{0}; 7 | 8 | cout << "Please enter a number: "; 9 | cin >> x; 10 | 11 | bool success{false}; 12 | while (!success) { 13 | if (cin.good()) { 14 | cout << "You entered the number " << x << "\n"; 15 | success = true; 16 | } 17 | else if (cin.fail()) { 18 | cout << "Please try again and enter a number\n"; 19 | cin.clear(); 20 | cin.ignore(20, '\n'); // Remove next 20 characters or everything up to next newline 21 | cin >> x; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /stream_memfns_and_state/recover4.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int x{0}; 8 | 9 | cout << "Please enter a number: "; 10 | cin >> x; 11 | 12 | bool success{false}; 13 | while (!success) { 14 | if (cin.good()) { 15 | cout << "You entered the number " << x << "\n"; 16 | success = true; 17 | } 18 | else if (cin.fail()) { 19 | cout << "Please try again and enter a number\n"; 20 | cin.clear(); 21 | //cin.ignore(20, '\n'); // Remove next 20 characters or everything up to next newline 22 | cin.ignore(numeric_limits::max(), '\n'); 23 | cin >> x; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /streams_and_buffering/flush.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | ofstream ofile{"log.txt"}; 8 | 9 | if (!ofile) { 10 | cout << "Could not open file\n"; 11 | return -1; 12 | } 13 | 14 | for (int i = 0; i < 1'000'000; ++i) { 15 | cout << i << "\n"; 16 | ofile << i << "\n"; 17 | 18 | //if (i == 66666) 19 | //throw std::exception(); 20 | } 21 | 22 | ofile.close(); 23 | } -------------------------------------------------------------------------------- /streams_and_buffering/flush2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | ofstream ofile("log.txt"); 8 | 9 | if (!ofile) { 10 | cout << "Could not open file\n"; 11 | return -1; 12 | } 13 | 14 | for (int i = 0; i < 1'000'000; ++i) { 15 | cout << i << endl; 16 | ofile << i << endl; 17 | } 18 | 19 | ofile.close(); 20 | } -------------------------------------------------------------------------------- /string_literals/raw.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // String literal with escaped characters 7 | string url = "C:\\\"Program Files\"\\\\n"; 8 | cout << "URL is " << url << endl << endl; 9 | 10 | // Raw string literal with unescaped characters 11 | string raw_url = R"(C:\"Program Files"\\n)"; 12 | cout << "Raw URL is " << raw_url << endl << endl; 13 | 14 | // Raw string literal with delimiter x 15 | string delimited_url = R"x(C:\"Program Files (x86)"\\n)x"; 16 | cout << "Delimited URL is " << delimited_url << endl << endl; 17 | } -------------------------------------------------------------------------------- /string_literals/string.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | using namespace std::literals; 6 | 7 | int main() { 8 | const char *cca = "Hello, world!"; 9 | cout << "cca: " << cca << endl; 10 | 11 | string str = "Hello, world!"s; 12 | cout << "str: " << str << endl; 13 | 14 | cout << "std::string literal: " << "Hello"s + ", world!"s << endl; 15 | } 16 | -------------------------------------------------------------------------------- /stringstreams/data.txt: -------------------------------------------------------------------------------- 1 | 23 45 6 1 8 2 | 19 27 46 33 99 12 3 | 6 79 4 | 48 34 68 73 -------------------------------------------------------------------------------- /stringstreams/istringstream.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | ifstream infile("data.txt"); 10 | 11 | if (!infile) { 12 | cout << "Could not open data.txt" << endl; 13 | return -1; 14 | } 15 | string line; 16 | vector numbers; 17 | 18 | while (getline(infile, line)) { 19 | // Validation etc 20 | istringstream is(line); 21 | int num; 22 | while (is >> num) { 23 | numbers.push_back(num); 24 | } 25 | } 26 | 27 | double sum{0.0}; 28 | for (auto n: numbers) { 29 | cout << n << endl; 30 | sum += n; 31 | } 32 | 33 | cout << "Average is " << sum/numbers.size() << endl; 34 | } -------------------------------------------------------------------------------- /stringstreams/ostringstream.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | ostringstream ostr; 9 | string text; 10 | 11 | cout << "Please enter a word\n"; 12 | cin >> text; // Read some data 13 | ostr << setw(16) << text; // Start building up the output 14 | cout << "Please enter another word\n"; 15 | cin >> text; // Read more data and add it to the output 16 | ostr << setw(12) << text; 17 | 18 | // Call str() to access the output string 19 | cout << ostr.str() << endl; // Display the output string 20 | } -------------------------------------------------------------------------------- /stringstreams/to_string.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template 7 | string To_String(const T& t) { 8 | ostringstream os; 9 | os << t; 10 | return os.str(); 11 | } 12 | 13 | int main() { 14 | string hello { "Hello, " }; 15 | string pi { To_String(3.14159) }; 16 | hello += pi; 17 | cout << hello << endl; 18 | } -------------------------------------------------------------------------------- /template_specialization/partial.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Generic Vector class 6 | template 7 | class Vector { 8 | public: 9 | void identify() { 10 | cout << "Vector\n"; 11 | } 12 | }; 13 | 14 | // Partial specialization of Vector class for pointers 15 | template 16 | class Vector { 17 | public: 18 | void identify() { 19 | cout << "Vector\n"; 20 | } 21 | }; 22 | 23 | int main() { 24 | Vector vec; 25 | Vector ptr_vec; 26 | 27 | cout << "vec identify: "; 28 | vec.identify(); 29 | cout << "vec identify: "; 30 | ptr_vec.identify(); 31 | } -------------------------------------------------------------------------------- /template_specialization/specialization.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Generic Vector class 6 | template 7 | class Vector { 8 | public: 9 | void identify() { 10 | cout << "Vector\n"; 11 | } 12 | }; 13 | 14 | // Specialization of Vector class for bool type 15 | template <> 16 | class Vector { 17 | public: 18 | void identify() { 19 | cout << "Vector\n"; 20 | } 21 | }; 22 | 23 | int main() { 24 | Vector ivec; 25 | Vector bvec; 26 | 27 | cout << "Vector identify: "; 28 | ivec.identify(); 29 | cout << "Vector identify: "; 30 | bvec.identify(); 31 | } -------------------------------------------------------------------------------- /templates_overview/argument_deduction_in_cpp17.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | //vector vec{1, 2, 3}; // C++11 - declared as vector 9 | vector vec{1, 2, 3}; // C++17 - deduced as vector 10 | 11 | cout << "vec = "; 12 | for (auto it : vec) 13 | cout << it << ", "; 14 | } -------------------------------------------------------------------------------- /templates_overview/func.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Function template for finding maximum of two values 6 | template // T is the parameter type 7 | T Max(const T& t1, const T& t2) { // The arguments and return value have this type 8 | if (t1 > t2) 9 | return t1; 10 | return t2; 11 | } 12 | 13 | int main() { 14 | cout << Max(7.0, 2.6) << endl; // Expands template to: 15 | 16 | /* 17 | double Max(const double& t1, const double& t2) { // The arguments and return value have this type 18 | if (t1 > t2) 19 | return t1; 20 | return t2; 21 | } 22 | */ 23 | } -------------------------------------------------------------------------------- /trad_pointers/array_allocation.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int *pa = new int[20]; 7 | 8 | for (int i = 0; i < 20; ++i) { 9 | pa[i] = i; 10 | } 11 | 12 | for (int i = 0; i < 20; ++i) { 13 | cout << pa[i] << ", "; 14 | } 15 | cout << endl; 16 | 17 | delete [] pa; 18 | } -------------------------------------------------------------------------------- /trad_pointers/pass_by_address.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void change_arg(int *arg) { 6 | cout << "Before modification, arg = " << arg << ", *arg = " << *arg << endl; 7 | *arg = 2; // arg behaves as a pointer 8 | cout << "After modification, arg = " << arg << ", *arg = " << *arg << endl; 9 | } 10 | 11 | int main() { 12 | int x{1}; // x is a stack variable 13 | cout << "Before calling change(), x = " << x << endl; 14 | change_arg(&x); // We pass the address of x 15 | cout << "After calling change(), x = " << x << endl; 16 | } -------------------------------------------------------------------------------- /trad_pointers/stack.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int i{1}; // i is a stack variable 7 | int *p1 = &i; // p1 is a pointer to int. Its value is the address of i 8 | cout << "Value of p1 is " << p1 << endl; 9 | cout << "Data stored in p1 is " << *p1 << endl; 10 | } -------------------------------------------------------------------------------- /try_catch_blocks/catch_elsewhere.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Function which throws an unhandled exception 7 | void func(const vector& vec) { 8 | cout << vec.at(2) << endl; // Throws an exception 9 | } 10 | 11 | int main() { 12 | vector vec; 13 | 14 | // Catch any exceptions thrown by func() 15 | try { 16 | func(vec); 17 | } 18 | // Handle the exception 19 | catch (const std::exception& e) { 20 | cout << "std::exception catch block\n"; 21 | cout << "Exception caught: " << e.what() << endl; // Print out a description of the exception 22 | } 23 | } -------------------------------------------------------------------------------- /try_catch_blocks/nested.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | vector vec; 8 | try { 9 | try { 10 | cout << vec.at(2) << endl; // Throws an exception 11 | } 12 | catch (const std::bad_alloc& e) { 13 | cout << "Runtime error catch block\n"; 14 | cout << "Exception caught: " << e.what() << endl; // Print out a description of the exception 15 | } 16 | } 17 | catch (const std::exception& e) { // Will handle all subclasses of std::exception 18 | cout << "std::exception catch block\n"; 19 | cout << "Exception caught: " << e.what() << endl; // Print out a description of the exception 20 | } 21 | } -------------------------------------------------------------------------------- /try_catch_blocks/order.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | try { 8 | vector v; 9 | cout << v.at(2) << endl; // May throw an exception of type std::out_of_range 10 | } 11 | catch (const exception& e) { // Will handle all sub-classes of std::exception 12 | cout << "std::exception\n"; 13 | } 14 | catch (const out_of_range& e) { // Only handles exceptions of type std::out_of_range 15 | cout << "std::out_of_range\n"; 16 | } 17 | // Which catch block handles the exception? 18 | } -------------------------------------------------------------------------------- /try_catch_blocks/order2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | try { 8 | vector v; 9 | cout << v.at(2) << endl; // May throw an exception of type std::out_of_range 10 | } 11 | catch (const out_of_range& e) { // Only handles exceptions of type std::out_of_range 12 | cout << "std::out_of_range\n"; 13 | } 14 | catch (const exception& e) { // Will handle all sub-classes of std::exception 15 | cout << "std::exception\n"; 16 | } 17 | // Which catch block handles the exception? 18 | } -------------------------------------------------------------------------------- /tuples/return.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | tuple func() { 8 | return {1.0, 2, "Three"s}; // Return the tuple from the function 9 | } 10 | 11 | int main() { 12 | double d; 13 | int i; 14 | string str; 15 | tie(d, i, str) = func(); // Unpack the tuple in the caller 16 | 17 | cout << "Elements of returned tuple are: " << d << ", " << i << R"(, ")" << str << R"(")" << endl; 18 | } -------------------------------------------------------------------------------- /tuples/tie.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | tuple numbers(1.0, 2, "Three"s); 9 | 10 | double d; 11 | int i; 12 | string str; 13 | 14 | tie(d, i, str) = numbers; // Store all elements in variables 15 | 16 | cout << "Tuple elements are: " << d << ", " << i << R"(, ")" << str << R"(")" << endl; 17 | } -------------------------------------------------------------------------------- /tuples_in_cpp17/apply.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | void func(int i, double d, string s) { 9 | cout << "i = " << i << ", d = " << d << ", s = " << s << endl; 10 | } 11 | 12 | int main() { 13 | apply(func, tuple(1, 2.0, "three"s)); // Calls func(1, 2.0, "three"s); 14 | } -------------------------------------------------------------------------------- /tuples_in_cpp17/make_from_tuple.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct Test { 9 | int i; 10 | double d; 11 | string s; 12 | Test(int i, double d, string s) : i(i), d(d), s(s) {} 13 | void print() { 14 | cout << "i = " << i << ", d = " << d << ", s = " << s << endl; 15 | } 16 | }; 17 | 18 | int main() { 19 | auto test = make_from_tuple(tuple(1, 2.0, "three"s)); // Calls Test(1, 2.0, "three"s); 20 | test.print(); 21 | } -------------------------------------------------------------------------------- /two_dimensional_arrays/flattened.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | string names[] = { 7 | "Fred", "Wilma", "Pebbles", "Dino", "Barney", "Betty", "Bamm-Bamm", "Hoppy" 8 | }; 9 | 10 | cout << "names[1][2] = " << names[1*4 + 2] << endl; 11 | 12 | cout << "\nThe elements of names are:\n"; 13 | for (int row = 0; row < 2; ++row) { 14 | for (int col = 0; col < 4; ++col) { 15 | cout << names[row*4 + col] << ", "; 16 | } 17 | cout << "\n"; 18 | } 19 | } -------------------------------------------------------------------------------- /two_dimensional_arrays/iteration.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | string names[2][4] = { 7 | {"Fred", "Wilma", "Pebbles", "Dino"}, 8 | {"Barney", "Betty", "Bamm-Bamm", "Hoppy"} 9 | }; 10 | 11 | cout << "names[1][2] = " << names[1][2] << endl; 12 | 13 | cout << "\nThe elements of names are:\n"; 14 | for (int row = 0; row < 2; ++row) { 15 | for (int col = 0; col < 4; ++col) { 16 | cout << names[row][col] << ", "; 17 | } 18 | cout << "\n"; 19 | } 20 | } -------------------------------------------------------------------------------- /unbuffered_input_and_output/get_put.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | cout << "Enter some text:" << endl; 7 | 8 | char c; 9 | while (cin.get(c)) // Read a character until we get end-of-input 10 | cout.put(c); // Display the character 11 | } -------------------------------------------------------------------------------- /unbuffered_input_and_output/input.txt: -------------------------------------------------------------------------------- 1 | 0123456789 -------------------------------------------------------------------------------- /unions/union.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | union Token { 6 | // Members are public by default 7 | char c; 8 | int i; 9 | double d; 10 | }; 11 | 12 | int main() { 13 | Token token; 14 | token.c = 'Z'; // char member is in use 15 | 16 | cout << token.d << endl; // Double member not in use - has undefined value 17 | } -------------------------------------------------------------------------------- /unions_continued/variant.cc: -------------------------------------------------------------------------------- 1 | // Requires C++17 compiler 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | variant v; 9 | v = 'Z'; // char member is in use 10 | 11 | if (holds_alternative(v)) 12 | cout << get(v) << endl; 13 | else 14 | cout << "Double member not in use\n"; 15 | } -------------------------------------------------------------------------------- /unique_pointer/argument.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Data structure representing a point on the screen 7 | struct Point { 8 | int x; 9 | int y; 10 | }; 11 | 12 | void func(unique_ptr upp) { 13 | cout << upp->x << ", " << upp->y << endl; 14 | } 15 | 16 | int main() { 17 | auto p{ make_unique( Point{3, 6} )}; // Create local unique_ptr object 18 | func(std::move(ptr)); 19 | } -------------------------------------------------------------------------------- /unique_pointer/example.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Data structure representing a point on the screen 7 | struct Point { 8 | int x; 9 | int y; 10 | }; 11 | 12 | int main() { 13 | // Create a unique_ptr to an point which has initial value {3,6} 14 | auto p{ make_unique( Point{3, 6} ) }; 15 | //unique_ptr p{ new Point{3, 6} }; // C++11 16 | 17 | cout << p->x << ", " << p->y << endl; 18 | } -------------------------------------------------------------------------------- /unique_pointer/return2.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Data structure representing a point on the screen 7 | struct Point { 8 | int x; 9 | int y; 10 | }; 11 | 12 | unique_ptr point_ptr(int x, int y) { 13 | Point p = {x, y}; // Create Point object 14 | 15 | return make_unique(p); // Create and return unique_ptr object 16 | } 17 | 18 | int main() { 19 | auto upp {point_ptr(3, 6) }; 20 | 21 | cout << upp->x << ", " << upp->y << endl; 22 | } -------------------------------------------------------------------------------- /unordered_associative_containers/unordered_map.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | unordered_map scores; // Create unordered_map object 8 | scores.insert( {"Graham", 78} ); // Add some elements to it 9 | scores.insert( {"Grace", 66} ); 10 | scores.insert( {"Graham", 66} ); // Add duplicate elements 11 | scores.insert( {"Graham", 72} ); 12 | scores.insert( {"Hareesh", 77} ); 13 | 14 | for (auto it: scores) 15 | cout << it.first << " has a score of " << it.second << endl; 16 | } -------------------------------------------------------------------------------- /variadic_templates/sizeof.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template // Args is a list of types (template parameter pack) 7 | void func(Args... args) { // args is a list of arguments whose types match Args 8 | cout << "Compiler has deduced call with " << sizeof...(args) << " argument(s)\n"; 9 | } 10 | 11 | int main() { 12 | int i{42}; double d{0.0}; string s{"text"}; 13 | 14 | func(s); // Instantiated as func(string); 15 | func(i, d, s); // Instantiated as func(int, double, string); 16 | } 17 | -------------------------------------------------------------------------------- /variadic_templates/tuple.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | template // Args is a list of types (template parameter pack) 8 | void func(Args... args) { // args is a list of arguments whose types match Args 9 | auto arg_tuple = make_tuple(args...); // Store the arguments in a tuple 10 | auto first = get<0>(arg_tuple); 11 | cout << "First argument is " << first << endl; 12 | } 13 | 14 | int main() { 15 | int i{42}; double d{0.0}; string s{"text"}; 16 | 17 | func(i, d, s); // Instantiated as func(int, double, string); 18 | } -------------------------------------------------------------------------------- /virtual_functions_in_cpp11/final_class.cc: -------------------------------------------------------------------------------- 1 | class Shape { 2 | public: 3 | virtual void draw() const; 4 | }; 5 | 6 | class Circle final : public Shape { 7 | public: 8 | void draw() const override; 9 | }; 10 | 11 | class DeluxeCircle : public Circle { 12 | public: 13 | void draw() const override; // Error! Overriding final function 14 | }; 15 | -------------------------------------------------------------------------------- /virtual_functions_in_cpp11/final_member.cc: -------------------------------------------------------------------------------- 1 | class Shape { 2 | public: 3 | virtual void draw() const; 4 | }; 5 | 6 | class Circle : public Shape { 7 | public: 8 | void draw() const override final; 9 | }; 10 | 11 | class DeluxeCircle : public Circle { 12 | public: 13 | void draw() const override; // Error! Overriding final function 14 | }; 15 | -------------------------------------------------------------------------------- /virtual_functions_in_cpp11/override.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Shape { 6 | public: 7 | virtual void draw() const { cout << "Drawing a generic shape...\n"; } 8 | }; 9 | 10 | class Circle : public Shape { 11 | public: 12 | void draw() const override { cout << "Drawing a circle...\n"; } // OK - overrides Shape::draw() 13 | //void draw(int radius) const override; // Error! Does not override 14 | }; 15 | 16 | int main() { 17 | Circle circle; 18 | circle.draw(); 19 | } 20 | -------------------------------------------------------------------------------- /virtual_inheritance/non_virtual.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Employee { 6 | public: 7 | void address() { cout << "Employee address = " << static_cast(this) << endl; } 8 | }; 9 | 10 | class SalesEmployee: public Employee { 11 | }; 12 | 13 | class Manager: public Employee { 14 | }; 15 | 16 | class SalesManager: public SalesEmployee, public Manager { 17 | }; 18 | 19 | int main() { 20 | SalesManager sm; 21 | 22 | cout << "Cast to SalesEmployee\n"; 23 | SalesEmployee* se{static_cast(&sm)}; 24 | se->address(); 25 | 26 | cout << "Cast to Manager\n"; 27 | Manager* m{static_cast(&sm)}; 28 | m->address(); 29 | } -------------------------------------------------------------------------------- /virtual_inheritance/virtual.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Employee { 6 | public: 7 | void address() { cout << "Employee address = " << static_cast(this) << endl; } 8 | }; 9 | 10 | class SalesEmployee: public virtual Employee { 11 | }; 12 | 13 | class Manager: public virtual Employee { 14 | }; 15 | 16 | class SalesManager: public SalesEmployee, public Manager { 17 | }; 18 | 19 | int main() { 20 | SalesManager sm; 21 | 22 | cout << "Cast to SalesEmployee\n"; 23 | SalesEmployee* se{static_cast(&sm)}; 24 | se->address(); 25 | 26 | cout << "Cast to Manager\n"; 27 | Manager* m{static_cast(&sm)}; 28 | m->address(); 29 | } -------------------------------------------------------------------------------- /weak_pointer/alias_dangle.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | // Create pointer 7 | int *ptr = new int(36); 8 | cout << "ptr's data is " << *ptr << endl; 9 | 10 | // Create pointer which is an alias to ptr 11 | int *wptr = ptr; 12 | 13 | // Release ptr's memory 14 | delete ptr; 15 | 16 | // How do we know if wptr is still valid? 17 | cout << "wptr's data is " << *wptr << endl; 18 | } -------------------------------------------------------------------------------- /weak_pointer/queue_dangle.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print(vector> vec) { 8 | cout << "Vector elements: "; 9 | 10 | for (shared_ptr p : vec) { 11 | cout << *p << ", "; 12 | } 13 | 14 | cout << endl; 15 | } 16 | 17 | int main() { 18 | vector> vec { 19 | make_shared(36), 20 | make_shared(42), 21 | make_shared(46), 22 | make_shared(50) 23 | }; 24 | 25 | print(vec); 26 | 27 | cout << "Deleting vec[2]\n"; 28 | vec[2] = nullptr; 29 | 30 | print(vec); 31 | } -------------------------------------------------------------------------------- /write_algorithms/replace.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void print(const vector& vec) { 8 | for (auto v : vec) 9 | cout << v << ", "; 10 | cout << endl; 11 | } 12 | 13 | int main() { 14 | // Replace all occurrences of 1 with 2 15 | vector vec{3, 1, 4, 1, 5, 9}; 16 | 17 | cout << "vec: "; 18 | print(vec); 19 | 20 | replace(begin(vec), end(vec), 1, 2); 21 | 22 | cout << "Vector after replace: "; 23 | print(vec); 24 | 25 | vector vec2{3, 1, 4, 1, 5, 9}; 26 | for (auto& v : vec2) // Equivalent loop 27 | if (v == 1) 28 | v = 2; 29 | 30 | cout << "Vector after loop: "; 31 | print(vec2); 32 | } -------------------------------------------------------------------------------- /write_only_algorithms/fill.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec(10); // Vector with 10 elements 9 | fill(begin(vec), end(vec), 42); // Assign 42 to all its elements 10 | 11 | cout << "Vector populated by fill: "; 12 | 13 | for (auto v: vec) 14 | cout << v << ", "; 15 | 16 | cout << endl; 17 | 18 | vector vec2(10); // Vector with 10 elements 19 | for (auto& v : vec2) 20 | v = 42; 21 | 22 | cout << "Vector populated by loop: "; 23 | for (auto v: vec2) 24 | cout << v << ", "; 25 | 26 | cout << endl; 27 | } -------------------------------------------------------------------------------- /write_only_algorithms/fill_n.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | // Assign the first 10 elements to 42 and the rest to 99 9 | vector vec(10); // Vector with 10 elements 10 | 11 | auto begin_rest = fill_n(begin(vec), 5, 42); // Assign 42 to the first 5 elements 12 | fill (begin_rest, end(vec), 99); // Assign 99 to the remaining elements 13 | 14 | /* 15 | int i; 16 | for (i = 0; i < 5; ++i) 17 | vec[i] = 42; 18 | for (; i < 10; ++i) 19 | vec[i] = 99; 20 | */ 21 | for (auto v: vec) 22 | cout << v << ", "; 23 | cout << endl; 24 | } -------------------------------------------------------------------------------- /write_only_algorithms/fill_n_bug.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec; // Create an empty vector 9 | 10 | // Assign 42 to the first 5 elements 11 | auto begin_rest = fill_n(begin(vec), 5, 42); 12 | } -------------------------------------------------------------------------------- /write_only_algorithms/fill_n_no_bug.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec; // Define empty vector 9 | 10 | // Resize vec to have 5 elements 11 | if (vec.size() < 5) { 12 | vector new_vec(5); 13 | vec.swap(new_vec); 14 | } 15 | 16 | auto begin_rest = fill_n(begin(vec), 5, 42); 17 | 18 | for (auto v: vec) 19 | cout << v << ", "; 20 | cout << endl; 21 | } -------------------------------------------------------------------------------- /write_only_algorithms/fill_n_no_bug_inserter.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | vector vec; // Define empty vector 9 | 10 | auto begin_rest = fill_n(back_inserter(vec), 5, 42); 11 | 12 | /* 13 | for (int i = 0; i < 5; ++i) 14 | vec.push_back(42); 15 | */ 16 | 17 | for (auto v: vec) 18 | cout << v << ", "; 19 | cout << endl; 20 | } -------------------------------------------------------------------------------- /write_only_algorithms/generate.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class square { 8 | private: 9 | int n{0}; 10 | public: 11 | int operator()() { ++n; return n * n; } 12 | }; 13 | 14 | int main() { 15 | vector vec(10); // Vector with 10 elements 16 | generate(begin(vec), end(vec), square()); // Populate it with the first 10 squares 17 | /* 18 | square sq; 19 | for (auto& v : vec) 20 | v = sq(); 21 | */ 22 | for (auto v : vec) 23 | cout << v << ", "; 24 | cout << endl; 25 | } -------------------------------------------------------------------------------- /write_only_algorithms/generate_n.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class square { 8 | private: 9 | int n{0}; 10 | public: 11 | int operator()() { ++n; return n * n; } 12 | }; 13 | 14 | int main() { 15 | vector vec; // Empty vector 16 | generate_n(back_inserter(vec), 10, square()); // Populate it with the first 10 squares 17 | /* 18 | square sq; 19 | for (int i = 0; i < 10; ++i) 20 | vec.push_back(sq()); 21 | */ 22 | for (auto v : vec) 23 | cout << v << ", "; 24 | cout << endl; 25 | } --------------------------------------------------------------------------------