【发布时间】:2011-02-07 07:18:07
【问题描述】:
我持有一个指向向量元素的迭代器,我想将它与向量的下一个元素进行比较。
这就是我所拥有的
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 没有给我向量的下一个元素。
我虽然 operator+ 是要走的路,但似乎并非如此。有解决办法吗?
谢谢
【问题讨论】:
-
您能否详细说明为什么您认为
next不是指当前之后的元素? -
你能澄清一下“但是 current + 1 没有给我向量的下一个元素。” ?
-
只是一个小旁注:你需要说
typename Vector<Point>::iterator begin(和end,和current)。即使代码按原样编译,标准也不需要它。一般来说,只要有class_template<T>::some_type obj,就必须在它前面加上typename,以确保编译器理解some_type是一个类型而不是别的东西。 -
@wilhelmtell:不,标准没有要求,除非
Point是模板参数。 TTBOMK、C++98 甚至不允许您将typename用于非依赖类型。 (ISTR litb 解释说 C++03 允许它,但我不确定,至少一个流行的当前编译器明确禁止它。) -
@wilhelmtell - 不正确。仅当类型依赖于另一个模板参数时才需要使用 typename。即
template <class T> typename vector<T>::iterator ...