简体   繁体   中英

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

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 .

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM