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

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不包括我们这样做的成员函数。)


当前回答

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

其他回答

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

在c++ 20中使用范围,你可以像这样使用std::ranges::copy

#include <ranges>
std::map<int,int> mapints;
std::vector<int> vints;

std::ranges::copy(mapints | std::views::keys, std::back_inserter(vints));

如果你想要值而不是键

std::ranges::copy(mapints | std::views::values, std::back_inserter(vints));

如果你不喜欢管道语法

std::ranges::copy(std::views::values(mapints), std::back_inserter(vints));

你的解决方案是好的,但你可以使用迭代器来做:

std::map<int, int> m;
m.insert(std::pair<int, int>(3, 4));
m.insert(std::pair<int, int>(5, 6));
for(std::map<int, int>::const_iterator it = m.begin(); it != m.end(); it++)
{
    int key = it->first;
    int value = it->second;
    //Do something
}

基于@rust -parks解决方案,但在c++17中:

std::map<int, int> items;
std::vector<int> itemKeys;

for (const auto& [key, _] : items) {
    itemKeys.push_back(key);
}

稍微类似于这里的一个例子,从std::map使用角度进行了简化。

template<class KEY, class VALUE>
std::vector<KEY> getKeys(const std::map<KEY, VALUE>& map)
{
    std::vector<KEY> keys(map.size());
    for (const auto& it : map)
        keys.push_back(it.first);
    return keys;
}

像这样使用:

auto keys = getKeys(yourMap);