C++ 11基于范围的()循环的常见示例总是这样简单:
std::vector<int> numbers = { 1, 2, 3, 4, 5, 6, 7 };
for ( auto xyz : numbers )
{
std::cout << xyz << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下xyz是一个int.但是,当我们有像地图这样的东西时会发生什么?此示例中变量的类型是什么:
std::map< foo, bar > testing = { /*...blah...*/ };
for ( auto abc : testing )
{
std::cout << abc << std::endl; // ? should this give a foo? a bar?
std::cout << abc->first << std::endl; // ? or is abc an iterator?
}
Run Code Online (Sandbox Code Playgroud)
当遍历的容器很简单时,看起来基于范围的()循环将给我们每个项目,而不是迭代器.哪个好...如果它是迭代器,我们总是要做的第一件事就是取消引用它.
但是,当涉及到地图和多重映射等内容时,我会感到困惑.
(我仍然使用g …
目前我的解决方案是迭代地图来解决这个问题.
我看到有一种upper_bound方法可以使这个循环更快,但有更快或更简洁的方法吗?