chapter 04 exercise solution

master
Tibor Bizjak 2023-07-26 19:50:27 +02:00
parent b660b8f153
commit 2393586493
2 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,42 @@
#include <cstdint>
#include <iterator>
#include <vector>
namespace mystd
{
using It = std::vector<std::int32_t>::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

View File

@ -0,0 +1,24 @@
#include <iostream>
#include <vector>
#include "IteratorLib.h"
int main()
{
auto vector = std::vector<int>{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;
}