如何使用基于范围的for()循环与std :: map? [英] How to use range-based for() loop with std::map?

查看:174
本文介绍了如何使用基于范围的for()循环与std :: map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?
}

当被遍历的容器很简单时,看起来像基于范围()循环将给我们每个项目,而不是一个迭代器。这是很好的...如果它是迭代器,我们总是要做的第一件事是去引用它。

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.

但我很困惑,

(我仍然在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< K,V> :: value_type ,它是 typedef for std :: pair< const K,V& / code>。因此,您可以将它写成

Each element of the container is a map<K, V>::value_type, which is a typedef for std::pair<const K, V>. Consequently, you'd write this as

for (auto& kv : myMap) {
    std::cout << kv.first << " has value " << kv.second << std::endl;
}

为了效率,最好使循环中的参数参考。如果你想要一个只读视图的值,你也可以考虑使它 const

For efficiency, it is a good idea to make the parameter in the loop a reference. You could also consider making it const if you want a read-only view of the values.

这篇关于如何使用基于范围的for()循环与std :: map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆