我能否使用范围for循环来访问容器的迭代器而不是值类型?
以下是我想实现的示例代码(无法编译,因为x是一对):
#include <iostream>
#include <map>
using namespace std;
std::map<int, float> v;
int main()
{
for(auto x : v)
cout<<x->first<<", "<<x->second<<endl;
return 0;
}
->
更改为.
:for(auto x : v)
cout<<x.first<<", "<<x.second<<endl;
范围-based for
循环存在的原因是为了让你不必处理迭代器。如果你确实需要迭代器,你就必须手动编写循环,但实际上代码并不会更长:
for (auto it = begin(v), ite = end(v); it != ite; ++it)
//loop body
是的,使用适当的容器适配器可以包装迭代器,使operator*()
返回迭代器而不是值。
我认为boost带有这样的包装器。
也许没有。但我在SO上找到了一个:https://dev59.com/c2w05IYBdhLWcg3w6F8w#14920606
正如Xeo所观察到的那样,确实可以使用Boost来完成这个操作,因为counting_range
执行算术运算,它可以像整数一样很好地处理迭代器:
for (auto it : boost::counting_range(v.begin(), v.end()))
const auto&
)来获取x
,而不是非const值(auto
)。 - syam