【发布时间】:2014-05-16 13:31:23
【问题描述】:
我有一个 std::vector<MyClass*> container 指向某个类的对象的指针,并且想使用基于范围的 for 循环来迭代向量,就像这样
for (MyClass *item : container)
{
// Do stuff, not changing the container
}
在这个循环中,我想再循环一次容器,但从容器中的下一个元素开始。如果没有迭代器,我真的找不到这样做的方法,所以我的解决方案是只使用那些来代替
for (auto item1 = container.begin(); item1 != container.end(); ++item1)
{
for (auto item2 = item1.next(); item2 != container.end(); ++item2)
{
// Do stuff, not changing the container
}
}
我的问题是:有没有办法做到这一点,而不必诉诸迭代器?我意识到基于范围的 for 循环只是语法糖,并且确实使用迭代器,但我喜欢我的语法糖!
【问题讨论】:
-
如果没有迭代器,您将无法做到这一点。但是您可以避免放弃迭代整个集合的语法糖,请参阅this answer。
-
谢谢,看起来很有趣。
-
@user2079303 添加它作为答案,我会接受它。
-
见我的回答附录
标签: c++ c++11 for-loop vector iterator