doubt about dereference of iterators, c ++

0

In my program I have created a linked list and I want to go through it with an iterator and in a position x modify a value in the list. I've been searching the internet and I've seen several examples but none of them work for me, I think there's something basic that I'm doing wrong, the code:

...
list<Avion>::iterator it;   //creando iterador

it =  flotaAviones.begin(); //igualando iterador a principio de lista

while (*it == false)
{

in this line, after the point according to the examples that I have seen on the internet, all the methods and attributes of the avion class should come out, because with the iterator I am pointing to the place in the list where a plane type object is stored. Well this does not happen)

    
asked by HOLDTHEDOOR 04.10.2018 в 15:47
source

1 answer

3

That code has a major problem:

while (*it == false)

*it dereference the iterator ... what that line does is compare an object of type Avion with false . Draw your own conclusions ...

Additionally, I do not see where or how you are moving through the list ... although I assume that you do it somewhere and that part works.

std::list provides two iterators: begin and end . While the first returns an iterator at the beginning of the list, the second returns an iterator that indicates that you have reached the end of the list.

With all this, to iterate through the entire collection, you could do this:

for( it = flotaAviones.begin(); it != flotaAviones.end(); ++it )

Or, if you do not want to ask for the end in each iteration because it seems inefficient :

for( list<Avion>::iterator it = flotaAviones.begin(), itEnd = flotaAviones.end(); it != itEnd; ++it )

Or, if you can also afford the luxury to use the C ++ 11 standard (Data of 2011 ... a whole novelty !!!), you could use one of these two versions:

for( auto it = flotaAviones.begin(), itEnd = flotaAviones.end(); it != itEnd; ++it )

for( Avion& avion : flotaAviones )

Note that in this last case you do not have iterators, this for uses the iterators internally and gives you access to the elements of the list directly

    
answered by 04.10.2018 в 16:28