k_kaz k_kaz - 19 days ago 10
C++ Question

c++ custom iterator constructor

The following code prints the numbers from 0 to 9 with custom iterators. I compile with

g++ -std=c++11 -o test test.cpp


#include <iostream>

class some_class;

class some_class_iterator : public std::iterator<std::forward_iterator_tag, int>{ private:
friend class some_class;
int pointed;
some_class_iterator(int _pointed): pointed(_pointed){
std::cout << "over here" << std::endl;
}

public:
int poitned;

int operator*(){
return pointed;
}

const some_class_iterator& operator++(){
pointed++;
return *this;
}

bool operator!=(const some_class_iterator& other) const {
return this->pointed != other.pointed;
}

};

class some_class{
public:
typedef some_class_iterator iterator;

iterator begin(){
return some_class_iterator(0);
}

iterator end(){
return some_class_iterator(10);
}

};


int main(){

some_class a;
for (some_class::iterator i = a.begin(); i != a.end(); ++i) std::cout << *i << std::endl;

}


However, the output is not what i expected to be as
over here
is printed multiple times.
For example actual output is :

over here
over here
0
over here
1
over here
2
over here
3
over here
4
over here
5
over here
6
over here
7
over here
8
over here
9
over here


So who is causing the call on the constructor here?

My actual problem is on a binary search tree iterator where in the constructor i create a FIFO traversal with the nodes to be printed depending on (in, pre, post), so calling the constructor multiple times is costy.

Answer

Every iteration of your loop you call a.end(), which will create a new iterator and print "over here". You could print out the value of _pointed to see this. (The first "over here" is from the begin call).