问题描述
我正在尝试使用迭代器创建一组循环,并且我遇到了一些迭代器算法(我认为可行但不起作用)。
I'm trying to create a set of loops with iterators and I'm having trouble with some iterator arithmetic (that I thought was possible but is not working).
下面是一些代码:
for (list<Term>::iterator itr = final.begin(); itr != final.end(); itr++) {
for(list<Term>::iterator j = itr + 1; j != final.end(); j++) {
cout << itr->term << " " << j->term;
if(itr->term == j->term) {
//Do stuff
}
}
}
我要做的是让j从队列中的下一个位置开始。原因是我不想检查第一个项目。错误本身来自代码中我指定 itr + 1
的部分。现在我确定用指针可以像这样做算法,为什么它不能与列表迭代器一起使用(基本上是同样的东西?)
What I am trying to do is have j start at the next place in the queue along from itr. The reason for this is I don't want to check the first item against itself. The error itself comes from the part in the code where I have specified itr + 1
. Now I was sure with pointers you could do arithmetic like this, why is it not working with the list iterator (which is essentially the same thing?)
错误我是从我的IDE获取如下: main.cpp:237:48:错误:'itr + 1'
中的'operator +'不匹配。我再次认为你可以在迭代器上做这种算法,所以我不确定该怎样做才能使这个工作,我可以尝试一种替代实现吗?
The error I am getting from my IDE is as follows: main.cpp:237:48: error: no match for ‘operator+’ in ‘itr + 1’
. Again I thought you could do this sort of arithmetic on iterators so I'm not really sure what to do to make this work, is there an alternate implementation I could try?
推荐答案
list
具有双向迭代器,不支持 operator +
。您可以在C ++ 11中使用 std :: advance
或 std :: next
。
list
has bidirectional iterators, that doesn't support operator +
. You can use std::advance
, or std::next
in C++11.
for (list<Term>::iterator j = next(itr); j != final.end(); ++j)
或
list<Term>::iterator j = itr;
advance(j, 1); // or ++j
for (; j != final.end(); ++j)
这篇关于C ++列表迭代器算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!