在向量中的点处有基于范围的for循环开始 [英] Have range-based for loop start at point in vector

查看:167
本文介绍了在向量中的点处有基于范围的for循环开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向某个类对象的指针std::vector<MyClass*> container,并且想要使用基于范围的for循环在向量上进行迭代,例如

I have a std::vector<MyClass*> container of pointers to objects of some class, and want to iterate over the vector using a range-based for loop, like this

for (MyClass *item : container)
{
    // Do stuff, not changing the container
}

在此循环中,我想循环遍历容器一次,但要从容器中的下一个元素开始.如果没有迭代器,我真的找不到找到这种方法的方法,所以我的解决方案是只使用那些迭代器

Inside this loop I want to loop through the container one more time, but starting at the next element in the container. I couldn't really find a way of doing this without iterators, so my solution was to just use those instead

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循环只是语法糖,并且确实使用了迭代器,但是我喜欢我的语法糖!

My question is: is there any way of doing this, without having to resort to iterators? I realize range-based for loops are just syntactical sugar, and really uses iterators, but I like my syntactical sugar!

推荐答案

应OP的要求添加了我的评论作为答案.

Added my comment as an answer by request from OP.

没有迭代器就无法做到这一点.但是您可以避免放弃语法糖来迭代整个集合,请参见

You can't do that without iterators. But you can avoid giving up the syntactic sugar for iterating the entire collection, see this answer. I haven't tested that code, but a comment to that answer suggests boost::counting_range, which might be even better.

这篇关于在向量中的点处有基于范围的for循环开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆