C++
我有以下迭代循环:
for (it = container.begin(); it != container.end(); ++it) {
//my code here
}
我想提前结束这个迭代1. 我尝试了以下方法,但它不能编译:
for (it = container.begin(); it != container.end() - 1; ++it) { //subtract 1
//my code here
}
这该怎么做呢?谢谢。
C++
我有以下迭代循环:
for (it = container.begin(); it != container.end(); ++it) {
//my code here
}
for (it = container.begin(); it != container.end() - 1; ++it) { //subtract 1
//my code here
}
您可以迭代至s
集合的std::prev(s.end())
之前,注意容器为空的可能性:
#include <iterator> // for std::prev
auto first = s.begin();
auto last = s.empty() ? s.end() : std::prev(s.end()); // in case s is empty
for (auto it = first; it != last; ++it) { ... }
Note: std::prev
需要C++11支持。 C++03的替代方案为--s.end()
。
std::advance(s.end(), -1)
替换对std::prev(s.end)
的调用。 - juanchopanzastd::prev
:for (it = container.begin(); it != std::prev(container.end()); ++it) { //subtract 1
//my code here
}
寻找最后一个迭代器的C++98解决方案可以如下:
set.find(*set.rbegin())
另一种选择是使用未记录且不被人们推荐的选项。
it!= --set.end()
同样有效,当设置为空时(begin == end),其行为应该是未定义的
for (it = container.begin(); it != --result->container.end(); ++it) { //subtract 1
//my code here
}
std::set::iterator
是双向迭代器,这意味着您可以对其执行 --
和 ++
操作。但是,它不满足随机访问迭代器的要求,因此您不能使用 -
和 +
操作。
result->container.end() - 1
需要一个随机访问迭代器,但你只有一个双向迭代器。相反,你可能想要使用 --result->container.end()
。
此外,你可能不想每次重新计算它,虽然这并不是什么大问题:
for (auto i(begin(result->container)), e(--end(result->container)); i!=e; ++i) {
end(result->container)
而不是 result->container.end()
? - chew socksstd::end(result->container)
。 - bames53