C++11 基于范围的 for() 循环的常见示例总是像这样简单:
The common example for C++11 range-based for() loops is always something simple like this:
std::vector<int> numbers = { 1, 2, 3, 4, 5, 6, 7 };
for ( auto xyz : numbers )
{
std::cout << xyz << std::endl;
}
在这种情况下,xyz
是一个 int
.但是,当我们拥有地图之类的东西时会发生什么?这个例子中变量的类型是什么:
In which case xyz
is an int
. But, what happens when we have something like a map? What is the type of the variable in this example:
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?
}
当被遍历的容器很简单时,看起来基于范围的 for() 循环会给我们每个项目,而不是迭代器.这很好……如果是迭代器,我们总是要做的第一件事就是取消引用它.
When the container being traversed is something simple, it looks like range-based for() loops will give us each item, not an iterator. Which is nice...if it was iterator, first thing we'd always have to do is to dereference it anyway.
但我对地图和多地图等内容的期望感到困惑.
But I'm confused as to what to expect when it comes to things like maps and multimaps.
(我仍然使用 g++ 4.4,而基于范围的循环使用 g++ 4.6+,所以我还没有机会尝试它.)
(I'm still on g++ 4.4, while range-based loops are in g++ 4.6+, so I haven't had the chance to try it yet.)
容器的每个元素都是一个 map
,也就是一个 typedef
code> 用于 std::pair
.因此,在 C++17 或更高版本中,您可以编写
Each element of the container is a map<K, V>::value_type
, which is a typedef
for std::pair<const K, V>
. Consequently, in C++17 or higher, you can write
for (auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}
或作为
for (const auto& [key, value]: myMap) {
std::cout << key << " has value " << value << std::endl;
}
如果您不打算修改这些值.
if you don't plan on modifying the values.
在 C++11 和 C++14 中,您可以使用增强的 for
循环来单独提取每一对,然后手动提取键和值:
In C++11 and C++14, you can use enhanced for
loops to extract out each pair on its own, then manually extract the keys and values:
for (const auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
如果您想要值的只读视图,您也可以考虑标记 kv
变量 const
.
You could also consider marking the kv
variable const
if you want a read-only view of the values.
这篇关于如何在 std::map 中使用基于范围的 for() 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!