user2321611
user2321611

Reputation: 1079

Iterator over a list pointing to wrong elements

I have 2 variables: std::list lst; and std::list<A*>::iterator lstiter with A being a class. The lst is filled with pointers to the class! B is an other class that holds both variables.

Puts iterator at the begin of the list:

void B::iterstart() {
lstiter = lst.begin();
}

void B::iternext() { 
iteratend();
lstiter = ++lstiter;
}

void B::iterprev() {
iteratstart(); 
lstiter = --lstiter;
}
void B::iteratend() {
 if (lst.empty())
    throw -1;
if (lstiter == lst.end()) 
    throw "Error: end of list\n"; 
}

void B::iteratstart() {
if (lst.empty())
     throw -1; 
if (lstiter == lst.begin())
    throw "Error: begin of list\n"; 
}

(I also have a function that gets the pointer at the element in the list the iterator is pointing too at the moment. Iteratend and iteratstart throw an exception when there are no elements in the list and when I try to go past the last or first element. This is where my problem is! Now I call: iterstart(); iternext(); iternext(); iternext(); I never get the message!(End of list)

And I do have some other bugs too, Sometimes I call the procedure prev, but I get the return value of the procedure next! (But I want to try to solve the other problem first)

Upvotes: 0

Views: 177

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54325

This lstiter = ++lstiter is wrong. With an integer it might work but when used with complicated C++ objects it does not always perform correctly because it depends on the specific implementation of the increment and copy functions. Also, why would you want to do it? All you need is ++lstiter.

Upvotes: 1

Related Questions