简体   繁体   English

迭代器和2d向量

[英]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-- . mincost是一个2d向量,我想获取此vector<int>的最后一个vector<int>以及last-- I don't really understand about iterator :) . 我对迭代器不是很了解:)。 Help me !! 帮我 !! :D Thx ^^ :D Thx ^^

minconst.end() points to the element one-past-the-end of the vector minconst ; minconst.end()指向向量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. 然后,访问向量中的最后一个元素仅是*(minconst.end() - 1) ,依此类推。

The C++ Reference also has a description of iterators . 《 C ++参考》还对迭代器进行了描述

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 快速的Google搜索会带来很多好的参考,其中最重要的是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. 如果您不熟悉STL容器,则可以将end()迭代器想像成C字符串中的'\\ 0'字符-它们定义了结尾在哪里,但是它们携带的实际值没有用。 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. 一旦您对迭代器感到满意,请查找reverse_iterator。 As Effo mentioned, they are the best solution here. 正如Effo所说,它们是这里最好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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