views:

290

answers:

3
vector< vector<int> >::iterator temp = mincost.end();
vector<int> a = *temp;
if ( *temp != *(temp--) ) 
 return 0;

mincost is a 2d vector, I want to get the last vector<int> of this vector and last--. I don't really understand about iterator :) . Help me !! :D Thx ^^

A: 

It would probably be helpful to learn about iterators in general.

A quick google search leads to many good references, not the least of which is http://www.cppreference.com/wiki/stl/iterators

Good luck!

bobber205
I've searched but I don't really understand :D .
nXqd
+1  A: 

minconst.end() points to the element one-past-the-end of the vector minconst; it doesn't point to the last element in the vector.

Since you want the last two elements, you should first test to be sure the vector actually has two elements in it, otherwise inevitably you'll run into problems. Then, accessing the last elements in the vector is simply a matter of *(minconst.end() - 1) and so forth.

The C++ Reference also has a description of iterators.

James McNellis
Your one-past-the-end link is really useful :)
nXqd
A: 

If you're new to STL containers, think of the end() iterator as something like the '\0' character in C-strings - they define where the end is, but the actual value they carry isn't useful. If you dereference the end iterator, you'll get junk, or most probably an exception.

Try this:

       if (!mincost.empty())
       {
             //it contains atleast one 1-d vector and the 'end' iterator.
             iter = mincost.end();
             --iter;
             //dereference iter here.
       }

Once you're comfortable with thinking in terms of iterators, look up the reverse_iterator. As Effo mentioned, they are the best solution here.

Fox