在C ++中类Python循环枚举 [英] Python-like loop enumeration in C++

查看:159
本文介绍了在C ++中类Python循环枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在C ++ 11中查找元素的位置基于范围的for循环?

我有一个向量,我想迭代它,同时,访问每个单独的元素的索引(我需​​要传递元素和它的索引到一个函数)。我已经考虑了以下两个解决方案:

I have a vector and I would like to iterate it and, at the same time, have access to the indexes for each individual element (I need to pass both the element and its index to a function). I have considered the following two solutions:

std::vector<int> v = { 10, 20, 30 };

// Solution 1
for (std::vector<int>::size_type idx = 0; idx < v.size(); ++idx)
    foo(v[idx], idx);

// Solution 2
for (auto it = v.begin(); it != v.end(); ++it)
    foo(*it, it - v.begin());

我想知道是否可能有更紧凑的解决方案。类似于Python的枚举。这是我使用C ++ 11范围循环最接近的,但是必须在私有范围中定义循环之外的索引,看起来似乎是比1或2更糟糕的解决方案:

I was wondering whether there might be a more compact solution. Something similar to Python's enumerate. This is the closest that I got using a C++11 range-loop, but having to define the index outside of the loop in a private scope definitely seems to be like a worse solution than either 1 or 2:

{
    int idx = 0;
    for (auto& elem : v)
        foo(elem, idx++);
}

是否有任何方式

推荐答案

正如@Kos所说,这是一个很简单的事情,我真的看不到需要进一步简化,并且个人只是坚持传统的for循环的索引,除了我会丢弃 std :: vector< T> :: size_type 并使用 std :: size_t

As @Kos says, this is such a simple thing that I don't really see the need to simplify it further and would personally just stick to the traditional for loop with indices, except that I'd ditch std::vector<T>::size_type and simply use std::size_t:

for(std::size_t i = 0; i < v.size(); ++i)
    foo(v[i], i);

我不太热衷于解决方案2.它需要(有点隐藏)随机访问迭代器,不允许你轻松地交换容器,这是迭代器的优点之一。如果你想使用迭代器,并使其通用(当迭代器不是随机访问时,可能会造成性能损失),我建议使用 std :: distance

I'm not too keen on solution 2. It requires (kinda hidden) random access iterators which wouldn't allow you to easily swap the container, which is one of the strong points of iterators. If you want to use iterators and make it generic (and possibly incur a performance hit when the iterators are not random access), I'd recommend using std::distance:

for(auto it(v.begin()); it != v.end(); ++it)
    foo(*it, std::distance(it, v.begin());

这篇关于在C ++中类Python循环枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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