从unordered_map获取键和值的列表 [英] Obtaining list of keys and values from unordered_map

查看:556
本文介绍了从unordered_map获取键和值的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

unordered_map 向量)的最有效方法是什么>?

What is the most efficient way of obtaining lists (as a vector) of the keys and values from an unordered_map?

为具体起见,假设所讨论的地图是 unordered_map< string,double>
然后我想以 vector< string> 的形式获取键,并以 vector< double>的值获取键。 code>。

For concreteness, suppose the map in question is a unordered_map<string, double>. I'd then like to obtain the keys as a vector<string>, and the values as a vector<double>.

unordered_map<string, double> um;

vector<string> vs = um.enum_keys();
vector<double> vd = um.enum_values(); 

我可以遍历地图并收集结果,但是还有更多的
有效的方法?最好也有一种适用于常规地图的方法,因为我可能会改用

I can just iterate across the map and collect the result, but is there a more efficient method? It would be nice to have a method that also works for regular map, since I might switch to that.

推荐答案

好吧,您去了:

std::vector<Key> keys;
keys.reserve(map.size());
std::vector<Val> vals;
vals.reserve(map.size());

for(auto kv : map) {
    keys.push_back(kv.first);
    vals.push_back(kv.second);  
} 

效率可能可以提高,但是确实如此。不过,您在两个容器上进行操作,因此,实际上没有任何STL魔术可以掩盖这一事实。

Efficiency can probably be improved, but there it is. You're operating on two containers though, so there's not really any STL magic that can hide that fact.

正如Louis所说,这对于任何STL 地图 set 容器。

As Louis said, this will work for any of the STL map or set containers.

这篇关于从unordered_map获取键和值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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