Reputation: 756
I have this situation:
void methodB(list<int>::iterator myIt){
myIt++;
}
void methodA(){
list<int> * myList=new list<int>();
list<int>::iterator it=myList->begin();
//many insertion in myList ...
methodB(it);
//...
}
I want that, when methodB ends, the iterator is one position forward but I can't do this... if I'm in methodA() and many times call methodB(it), every time the iterator is copied and when the control return to methodA() the it variable is always in myList->begin(). How can I solve this problem? Thanks
Upvotes: 2
Views: 64
Reputation: 69882
A good model for this is std::next
, which returns a modified copy of the iterator:
list<int>::iterator
methodB(list<int>::iterator myIt){
myIt++;
return myIt;
}
void methodA(){
list<int> * myList=new list<int>();
list<int>::iterator it=myList->begin();
//many insertion in myList ...
it = methodB(it);
//...
}
https://en.cppreference.com/w/cpp/iterator/next
Note that container iterators are designed to be cheap to copy.
Upvotes: 2
Reputation: 17483
You need to pass it by reference, like:
void methodB(list<int>::iterator& myIt);
Upvotes: 2