如何从std :: map检索所有键(或值)? [英] How to retrieve all keys (or values) from a std::map?

查看:1047
本文介绍了如何从std :: map检索所有键(或值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我出来的可能方法之一:

This is one of the possible ways I come out:

struct RetrieveKey
{
    template <typename T>
    typename T::first_type operator()(T keyValuePair) const
    {
        return keyValuePair.first;
    }
};

map<int, int> m;
vector<int> keys;

// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());

// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));

当然,我们也可以通过定义另一个函数来检索地图中的所有值 RetrieveValues

Of course, we can also retrieve all values from the map by defining another functor RetrieveValues.

有没有其他方法来实现这一点? (我总是想知道为什么std :: map不包括成员函数为我们这样做。)

Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.)

推荐答案

你的解决方案应该工作,它可能很难阅读取决于你的同行程序员的技能水平。此外,它将功能从呼叫站点移开。这可以使维修更困难一点。

While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.

我不知道你的目标是让键进入一个向量或打印他们cout所以我做这两个。您可以尝试这样:

I'm not sure if your goal is to get the keys into a vector or print them to cout so I'm doing both. You may try something like this:

map<int, int> m;
vector<int> v;
for(map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
  v.push_back(it->first);
  cout << it->first << "\n";
}



如果您使用Boost,更简单:

Or even simpler, if you are using Boost:

map<int,int> m;
pair<int,int> me; // what a map<int, int> is made of
vector<int> v;
BOOST_FOREACH(me, m) {
  v.push_back(me.first);
  cout << me.first << "\n";
}



个人而言,我喜欢BOOST_FOREACH版本,因为打字更少,明确他们在做什么。

Personally, I like the BOOST_FOREACH version because there is less typing and it is very explicit about what it is doing.

这篇关于如何从std :: map检索所有键(或值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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