可能重复:
在C++ 11范围内查找元素的位置for循环?
我有一个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());
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更紧凑的解决方案.与Python的枚举类似的东西.这是我使用C++ 11范围循环时最接近的,但是必须在私有范围内定义循环外的索引,这似乎比1或2更糟糕的解决方案:
{
int idx = 0;
for (auto& elem : v)
foo(elem, idx++);
}
Run Code Online (Sandbox Code Playgroud)
是否有任何方法(可能使用Boost)以这样的方式简化最新的示例,使索引自包含到循环中?