iterators in lists

Oct 3, 2010 at 5:27pm
Hello , how do i set the iterator i to directly point at the last element of the list without stepping through the list in the usual way shown below.

std::list < mutantType*> ::const_iterator i;

for ( i = tempList.begin();
i != tempList.end();
++ i )


i understand tempList.end() points to the end of the list , not necessarily at the last element?.
Oct 3, 2010 at 5:34pm
list::end() returns an iterator to one past the last element
rbegin() returns a (reverse) iterator to the very last element
Oct 3, 2010 at 7:42pm
okay , i see ....

i have situation where i have a list called bunnyList containing mutantType objects, i want to create a new object using a constructor and add this object to my list. Like below.

bunnyList.push_front( new mutantType );


with the aid of the newly discovered rbegin pointer i want to look at the last object in the list i've just added and execute a member function from that object....-mutantType. In this case mutantType::printsummary().

J is my reverse iterator


J= bunnyList.rbegin();
(*j)-> printSummary();


I want to put all this in a for..next loop . Although i get no warnings or compiling errorss, i suspect something is going wrong??. As the loop cycles
J= bunnyList.rbegin(); points to the newly added object.

I there anything wrong with this approach???







Oct 3, 2010 at 9:06pm
What exactly do you want to do in that loop? ( And with the last object ? )
You can directly get the last item of the list ( not iterator ) using list::back
Topic archived. No new replies allowed.