From f3c8cad317a202ec8ded2b63ea3cf10790a6ec82 Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Sun, 22 Oct 2023 22:12:56 +0200 Subject: [PATCH] feat: range based for --- chapters/chapter_02/CMakeLists.txt | 9 +++---- chapters/chapter_02/include/range_based_for.h | 9 +++++++ chapters/chapter_02/src/range_based_for.cpp | 24 +++++++++++++++++++ src/main.cpp | 2 ++ 4 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 chapters/chapter_02/include/range_based_for.h create mode 100644 chapters/chapter_02/src/range_based_for.cpp diff --git a/chapters/chapter_02/CMakeLists.txt b/chapters/chapter_02/CMakeLists.txt index 6236fdc..f656efe 100644 --- a/chapters/chapter_02/CMakeLists.txt +++ b/chapters/chapter_02/CMakeLists.txt @@ -1,12 +1,13 @@ add_library( chapter_02 + src/constexp.cpp + src/if_constexpr.cpp + src/ifswitch.cpp src/initlist.cpp src/null.cpp - src/constexp.cpp - src/ifswitch.cpp + src/range_based_for.cpp src/structured_binding.cpp - src/type_inference.cpp - src/if_constexpr.cpp) + src/type_inference.cpp) target_compile_features(chapter_02 PUBLIC cxx_std_20) diff --git a/chapters/chapter_02/include/range_based_for.h b/chapters/chapter_02/include/range_based_for.h new file mode 100644 index 0000000..10f977f --- /dev/null +++ b/chapters/chapter_02/include/range_based_for.h @@ -0,0 +1,9 @@ +#pragma once + +#include "chapter_interface.h" + +class RangeBasedForTest : public ChapterTest { +public: + virtual void run() override; + virtual const char *name() const override { return "Range based for test"; } +}; diff --git a/chapters/chapter_02/src/range_based_for.cpp b/chapters/chapter_02/src/range_based_for.cpp new file mode 100644 index 0000000..bc5c27a --- /dev/null +++ b/chapters/chapter_02/src/range_based_for.cpp @@ -0,0 +1,24 @@ +#include +#include + +#include "range_based_for.h" + +void RangeBasedForTest::run() { + std::vector vals = {1, 2, 3, 4, 5}; + + std::cout << "vals: "; + for (auto val : vals) { + std::cout << val << " "; + } + std::cout << std::endl; + + for (auto &val : vals) { + val *= 2; + } + + std::cout << "vals: "; + for (auto val : vals) { + std::cout << val << " "; + } + std::cout << std::endl; +} diff --git a/src/main.cpp b/src/main.cpp index 4a567c3..ee52b78 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,6 +8,7 @@ #include "ifswitch.h" #include "initlist.h" #include "null.h" +#include "range_based_for.h" #include "structured_binding.h" #include "type_inference.h" #include "version.h" @@ -26,6 +27,7 @@ int main(int argc, char **argv) { chapter_2_tests.emplace_back(std::make_unique()); chapter_2_tests.emplace_back(std::make_unique()); chapter_2_tests.emplace_back(std::make_unique()); + chapter_2_tests.emplace_back(std::make_unique()); for (auto &test : chapter_2_tests) { std::cout << "\n" << test->name() << ":" << std::endl;