[英]C++ “=” operator behavior for a class with a private vector and iterator for it
[英]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+5
, it+=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.