stl - C++ iterator over certain elements in vector -
please forgive me if trivial question, i'm learning c++ , try wrap head around concepts. when comes iterators, i'm lost.
say have custom class representing data structure, , 1 of members vector of integers. want write bidirectional iterator class, outputs numbers in vector. there easy , instructive way? i'd prefer not using libraries other stl.
#include <vector> #include <iostream> class x { public: class eveniterator { public: eveniterator(std::vector<int>::iterator it, std::vector<int>::iterator end) : it(it), end(end) { while (true) { if (iseven(*it)) { break; } else if (it == end) { break; } it++; } } bool operator != (const eveniterator& evenit) { return evenit.it != this->it; } int operator * () { return *it; } eveniterator operator ++ () { while (true) { it++; if (iseven(*it)) { return eveniterator(it, end); } else if (it == end) { return eveniterator(it, end); } } } private: std::vector<int>::iterator it; std::vector<int>::iterator end; }; static bool iseven(int number) { return number % 2 == 0; } void add(int number) { v.push_back(number); } eveniterator evenbegin() { return eveniterator(v.begin(), v.end()); } eveniterator evenend() { return eveniterator(v.end(), v.end()); } private: std::vector<int> v; }; int main() { x x; x.add(1); x.add(2); x.add(3); x.add(2); x.add(2); x.add(31); x.add(56); x.add(101); (x::eveniterator = x.evenbegin(); != x.evenend(); ++it){ std::cout << *it << std::endl; // prints numbers } }
Comments
Post a Comment