03-4-2013, 07:46 PM | #1 |
Aficionado of Awk
|
C++ iterator question
using the following code:
list<string>::iterator iter; for (iter=names.begin(); iter!=names.end(); iter++) { names.erase(iter); } we are supposed to assume that the program compiles but does not execute properly (logical error causing a CRASH). The list holds 20 names. What is wrong, I don't see anything wrong with it (but I'm sort of new on the whole pointer thing)? names.end() points to the imaginary space after the last element in the list. begin() points at the first element of the list. my two guesses is that either: iter!=names.end() should be something else, or names.erase(iter) should be names.erase(*iter); |
03-4-2013, 08:02 PM | #2 |
FFR Player
|
Re: C++ iterator question
When you erase from std::list, you delete the reference to the iterator. In other words, after it is deleted, "iter++" has no idea where it needs to go next, because you just deleted "iter". You need to save where the iterator is in the list, so you just use the return value from erase(). All you would have to do to fix that code segment is change "names.erase(iter)" to "iter = names.erase(iter)" so you don't lose your position when you are traversing the list.
__________________
|
03-4-2013, 08:14 PM | #3 | |
Aficionado of Awk
|
Re: C++ iterator question
Quote:
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|