C ++ vector <t> :: iterator operator + </t>

时间:2010-04-13 05:34:28

标签: c++ iterator operators

我持有一个指向向量元素的迭代器,我想将它与向量的下一个元素进行比较。

这就是我所拥有的

Class Point{
public:
 float x,y;
}

//Somewhere in my code I do this

vector<Point> points = line.getPoints();

foo (points.begin(),points.end());

其中foo是:

void foo (Vector<Point>::iterator begin,Vector<Point>::iterator end)
{
    std::Vector<Point>::iterator current = begin;

    for(;current!=end-1;++current)
    {
        std::Vector<Point>::iterator next = current + 1;

        //Compare between current and next.
    }
}

我认为这会有效,但是current + 1没有给我矢量的下一个元素。

我虽然操作员+是要走的路,但似乎并非如此。有解决方法吗?

感谢

3 个答案:

答案 0 :(得分:3)

current + 1对随机访问迭代器(包括向量迭代器)有效,它是当前的迭代器(即你认为它的作用)。检查(或发布!)你的比较代码,你可能在那里做错了。

答案 1 :(得分:1)

std::vector随机访问迭代器。这意味着它们基本上就像指针一样多才多艺。它们提供全面的指针算法(it+5it+=2)和除!= / ==以外的比较(即<<=>>=)。

代码中的迭代器之间的比较肯定会起作用,但是没有意义:

for(std::vector<Point>::iterator current = begin;current!=end-1;++current)
{
    std::vector<Point>::iterator next = current + 1;

    assert(current!=next); // always true
    assert(current<next); // also always true
}

因此,如果它对您不起作用,则可能是您做错了。不幸的是,“......并没有给我矢量的下一个元素......”并没有让我们知道你在尝试什么,所以很难猜出你可能做错了什么。

答案 2 :(得分:0)

也许这只是一个错字,但您的代码是指Vector而标准容器是vector(小写V)。

但如果你的问题不是一个错字,如果没有看到Vector的定义,就没有办法说出它的作用。