Python-like loop enumeration in C++(C++ 中类似 Python 的循环枚举)
问题描述
可能的重复:
在 C++11 range-based 中查找元素的位置for 循环?
我有一个 vector
并且我想迭代它,同时可以访问每个单独元素的索引(我需要将元素及其索引传递给功能).我考虑了以下两种解决方案:
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 的 enumerate.这是我使用 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++);
}
有没有办法(也许使用 Boost)来简化最新的例子,使索引自包含到循环中?
Is there any way (perhaps using Boost) to simplify the latest example in such a way that the index gets self-contained into the loop?
推荐答案
正如@Kos 所说,这是一件如此简单的事情,我真的不认为有必要进一步简化它,个人只会坚持传统的使用索引循环,除了我会放弃 std::vector
并简单地使用 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 的循环枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中类似 Python 的循环枚举


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01