簡體   English   中英

C ++向量 <T> ::迭代器運算符+

[英]C++ vector<T>::iterator operator +

我持有一個指向向量元素的迭代器,我想將其與向量的下一個元素進行比較。

這是我所擁有的

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不能給我向量的下一個元素。

我雖然操作員+是要走的路,但似乎並非如此。 有沒有解決方法?

謝謝

current + 1對於隨機訪問迭代器(包括矢量迭代器)有效,並且是current之后的迭代器(即,您認為它執行的操作)。 檢查(或發布!)您的比較代碼,您可能在其中做錯了什么。

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
}

因此,如果這對您不起作用,則可能是您做錯了。 不幸的是,“ ...沒有給我向量的下一個元素...”並沒有給我們提供任何線索您正在嘗試的東西,因此很難猜測您可能做錯了什么。

也許這只是一個錯字,但您的代碼是指Vector而標准容器是vector (小寫V)。

但是,如果這不是您輸入中的錯字,而沒有看到Vector的定義,那么就沒有辦法告訴您這樣做是什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM