From 23935864935693e2c591bf7ead41bc359352ae6d Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Wed, 26 Jul 2023 19:50:27 +0200 Subject: [PATCH] chapter 04 exercise solution --- udemy-cpp/exc04/IteratorLib.h | 42 +++++++++++++++++++++++++++++++++++ udemy-cpp/exc04/main.cc | 24 ++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 udemy-cpp/exc04/IteratorLib.h create mode 100644 udemy-cpp/exc04/main.cc diff --git a/udemy-cpp/exc04/IteratorLib.h b/udemy-cpp/exc04/IteratorLib.h new file mode 100644 index 0000000..7faf546 --- /dev/null +++ b/udemy-cpp/exc04/IteratorLib.h @@ -0,0 +1,42 @@ +#include +#include +#include + +namespace mystd +{ + +using It = std::vector::iterator; +using DifferenceType = It::difference_type; + +/* advence: advances iterator it by n steps */ +void advance(It &it, DifferenceType n) +{ + it += n; +} + +/* distance: returns number of steps needed to go from first to last */ +DifferenceType distance(It first, It last) +{ + auto dist = DifferenceType{0}; + + for (; first < last; ++dist) + ++first; + for (; first > last; --dist) + --first; + + return dist; +} + +/* next: returns next iterator */ +It next(It it, DifferenceType n = 1) +{ + return it + n; +} + +/* prev: returns previous iterator */ +It prev(It it, DifferenceType n = 1) +{ + return it - n; +} + +} // namespace mystd diff --git a/udemy-cpp/exc04/main.cc b/udemy-cpp/exc04/main.cc new file mode 100644 index 0000000..6d38974 --- /dev/null +++ b/udemy-cpp/exc04/main.cc @@ -0,0 +1,24 @@ +#include +#include + +#include "IteratorLib.h" + +int main() +{ + auto vector = std::vector{1, 2, 3}; + auto vector_it = vector.begin(); + + auto next_it = mystd::next(vector_it); + std::cout << "*next_it: " << *next_it << '\n'; + + auto prev_it = mystd::prev(next_it); + std::cout << "*prev_it: " << *prev_it << '\n'; + + mystd::advance(vector_it, 2); + std::cout << "advance: " << *vector_it << '\n'; + + auto dist = mystd::distance(vector_it, vector.begin()); + std::cout << "distance: " << dist << '\n'; + + return 0; +}