【发布时间】:2012-07-04 21:49:14
【问题描述】:
可能重复:
Find position of element in C++11 range-based for loop?
我有一个vector,我想对其进行迭代,同时访问每个单独元素的索引(我需要将元素及其索引都传递给函数)。我考虑了以下两种解决方案:
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 更糟糕:
{
int idx = 0;
for (auto& elem : v)
foo(elem, idx++);
}
有没有什么方法(可能使用 Boost)来简化最新的示例,从而使索引自包含到循环中?
【问题讨论】:
-
为什么要简化简单的事情? :-)
-
您必须创建一个类似生成器的函数/对象,该函数/对象返回 std::pair 并使用该对的第一个和第二个字段。您可能可以使用宏来解决问题,但是在 C++ 中没有方便而优雅的方式来使用类似 Python 的语法。您的第二个解决方案可能是最好的办法。
-
@Kos 我对解决方案 2 非常满意。只是好奇是否有更简单的方法 :)
-
怎么样:` for ( auto x : v | boost::adaptors::indexed(0) ) { std::cout