I am trying to write a custom iterator for my Vector/Matrix class. The purpose of the iterator is to iterate through a std::vector and skip every n'th element. I already asked a similar question c++ implementing iterators for custom matrix class which indeed provides a solution to the problem.
However this approach is too slow. I did quite a bit of reading: Effective C++, C++ Primer etc. and on-line resources: http://www.drdobbs.com/stl-generic-programming-writing-your-ow/184401417 or How to correctly implement custom iterators and const_iterators? and of course: http://www.cplusplus.com/reference/iterator/iterator/.
The last one in particular provides a working code. However I can't really figure out what the code does and how to implement this for a std::vector. Here is the code:
template<class T>
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; return *this; }
bool operator!=(const iter& rhs) {return m_pter!=rhs.m_pter;}
T& operator*() { return *m_pter; }
};
and the main:
int main(int argc, char *argv[]){
int a[] = {1,2,3,4,5,6};
iter<int> from(a);
iter<int> to(a+5);
for (iter<int> iter = from; iter != to; ++iter) {
std::cout << *iter << std::endl;
}
// std::vector<int> a = {1,2,3,4,5,6};
// iter<std::vector<int> > from(a);
// iter<std::vector<int> > to(a+5);
// for (iter<std::vectorVECTOR<int> > iter=from; iter!=to; ++iter) {
// std::cout << *iter << std::endl;
// }
}
The upper part in the main function returns: $ ./main 1 2 3 4 5
and the lower part:
main.cpp:49:21: error: no matching function for call to ‘iter<int>::iter(std::vector<int>&)’
iter<int> from(a);
I would really like to understand why the code works for the array but not the vector. What would I need to change in order for it to work for the vector?
Your comments are greatly appreciated.
Vincent