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

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++ 0x给了我们一个更进一步的,优秀的解决方案:

std::vector<int> keys;

std::transform(
    m_Inputs.begin(),
    m_Inputs.end(),
    std::back_inserter(keys),
    [](const std::map<int,int>::value_type &pair){return pair.first;});

其他回答

这是一个使用c++ 11魔法的很好的函数模板,适用于std::map, std::unordered_map:

template<template <typename...> class MAP, class KEY, class VALUE>
std::vector<KEY>
keys(const MAP<KEY, VALUE>& map)
{
    std::vector<KEY> result;
    result.reserve(map.size());
    for(const auto& it : map){
        result.emplace_back(it.first);
    }
    return result;
}

点击这里查看:http://ideone.com/lYBzpL

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

我不确定你的目标是将键输入到向量中还是将它们打印到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版本,因为它的输入更少,而且它非常明确地说明了它在做什么。

//c++0x too
std::map<int,int> mapints;
std::vector<int> vints;
for(auto const& imap: mapints)
    vints.push_back(imap.first);

@丹丹的答案,使用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。

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