I am working on a custom iterator for my linear algebra library. I have the following code (slight modification of http://www.cplusplus.com/reference/iterator/iterator/)
template<class T, std::size_t Increment = 1>
class iter: public std::iterator<std::random_access_iterator_tag, T>{
private:
T* m_pter;
public:
iter(T* value): m_pter(value){}
iter(const iter& other_it): m_pter(other_it.m_pter){}
iter& operator++() { m_pter+=Increment; return *this; }
// iter& operator+() { m_pter += Increment; return *this; }
bool operator!=(const iter& rhs) {return m_pter!=rhs.m_pter;}
bool operator<(const iter& rhs) {return m_pter<rhs.m_pter;}
T& operator*() { return *m_pter; }
};
in the main:
int main(int argc, char *argv[]){
std::vector<int> a = {1,2,3,4,5,6,7,8,9};
iter<int, 2> from( &a[0] );
iter<int, 2> to( &a[8] + 1 );
for(;from < to;++from){std::cout << *from << std::endl;}
// std::for_each(from, to, [](int i){std::cout << i << " ";});
std::cout << std::endl;
}
returns: $ ./main 1 3 5 7 9
which is exactly what I want. However using std::for_each... version returns:
$ ./main
1 3 5 7 9 135121 0 0 many zeros ...
I have no idea why the std algorithm "jumps over" my last element.