c++ - 我可以从基于 for 循环的范围内获取项目的索引吗?

标签 c++ loops c++11 indexing range

我定义了一个像这样的指针双端队列:

std::deque<BoardSquare *> mydeque;

我想在我的双端队列中使用基于范围的 for 循环:

for (BoardSquare * b : mydeque) {

    // do something involving the index of b
}

是否可以从基于范围的 for 循环中获取项目的索引?

最佳答案

不,不是(至少不是以合理的方式)。当您确实需要索引时,您可能根本不应该使用基于范围的 for 循环,而应该使用一个很好的旧迭代器或基于索引的 for 循环:

// non-idiomatic index-iteration, random access containers only
for(std::size_t i=0; i<mydeque.size(); ++i)
    mydeque[i];

// awfully ugly additional iteration variable, yet generic and fast
std::size_t i = 0;
for(auto iter=mydeque.begin(); iter!=mydeque.end(); ++iter,++i)
    *iter;

// idiomatic and generic, yet slow for non-random access containers
for(auto iter=mydeque.begin(); iter!=mydeque.end(); ++iter)
{
    auto i = std::distance(mydeque.begin(), iter);
    *iter;
}

在清晰度、惯用性、流线型和性能方面,所有这些都有其优点和缺点。

关于c++ - 我可以从基于 for 循环的范围内获取项目的索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17749905/

相关文章:

c++ - 无法将 'this' 指针转换为类

c++ - boost 线程 : Term does not evaluate to function taking 0 arguments

javascript - 循环遍历分割数组并使用wrapInner输出

javascript - 如何在javascript中通过两个对象创建新对象

c++ - 使用 PInvoke 时,为什么要使用 __stdcall?

c++ - 默认字符串参数

php - 多维数组的递归循环?

c++ - 为什么以及如何额外的括号改变 C++ (C++11) 中表达式的类型?

c++ - 从 3 个数组中查找最大前 5 个数的优雅代码

c++ - std::vector::insert 是否按定义保留?