Tzu ng
Tzu ng

Reputation: 9244

Iterator and 2d vector

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 ^^

Upvotes: 0

Views: 975

Answers (3)

Fox
Fox

Reputation: 2138

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.

Upvotes: 0

James McNellis
James McNellis

Reputation: 355307

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.

Upvotes: 1

bobber205
bobber205

Reputation: 13372

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!

Upvotes: 0

Related Questions