这是我提出的一种可能的方法:

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从映射中检索所有值。

有没有其他方法可以轻松实现这个目标?(我总是想知道为什么std::map不包括我们这样做的成员函数。)


当前回答

@丹丹的答案,使用c++ 11是:

using namespace std;
vector<int> keys;

transform(begin(map_in), end(map_in), back_inserter(keys), 
            [](decltype(map_in)::value_type const& pair) {
    return pair.first;
}); 

使用c++ 14(如@ivan.ukr所述),我们可以将decltype(map_in)::value_type替换为auto。

其他回答

你可以从fplus库中使用get_map_keys():

#include<fplus/maps.hpp>
// ...

int main() {
    map<string, int32_t> myMap{{"a", 1}, {"b", 2}};
    vector<string> keys = fplus::get_map_keys(myMap);
    // ...
    return 0;
}

有一个升压范围适配器用于此目的:

#include <boost/range/adaptor/map.hpp>
#include <boost/range/algorithm/copy.hpp>
vector<int> keys;
boost::copy(m | boost::adaptors::map_keys, std::back_inserter(keys));

有一个类似的map_values范围适配器用于提取值。

SGI STL有一个名为select1st的扩展。可惜不是标准的STL!

c++11的一个小例子:

std::map<uint32_t, uint32_t> items;
std::vector<uint32_t> itemKeys;
for (auto & kvp : items)
{
    itemKeys.emplace_back(kvp.first);
    std::cout << kvp.first << std::endl;
}

虽然您的解决方案应该可以工作,但根据其他程序员的技能水平,它可能很难阅读。此外,它将功能从调用站点移走。这可能会使维护更加困难。

我不确定你的目标是将键输入到向量中还是将它们打印到cout中,所以我两者都做了。你可以尝试这样做:

std::map<int, int> m;
std::vector<int> key, value;
for(std::map<int,int>::iterator it = m.begin(); it != m.end(); ++it) {
  key.push_back(it->first);
  value.push_back(it->second);
  std::cout << "Key: " << it->first << std::endl();
  std::cout << "Value: " << it->second << std::endl();
}

或者更简单,如果你使用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版本,因为它的输入更少,而且它非常明确地说明了它在做什么。