将地图值复制到 STL 中的向量

新手上路,请多包涵

目前正在通过有效的 STL 工作。第 5 项建议使用范围成员函数通常比使用它们的单元素对应物更可取。我目前希望将地图中的所有值(即 - 我不需要键)复制到向量中。

最干净的方法是什么?

原文由 Gilad Naor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 531
2 个回答

您不能在这里轻松地使用范围,因为您从映射中获得的迭代器指的是 std::pair,您将用于插入向量中的迭代器指的是存储在向量中的类型的对象,即(如果您要丢弃密钥)不是一对。

我真的不认为它比显而易见的更干净:

 #include <map>
#include <vector>
#include <string>
using namespace std;

int main() {
    typedef map <string, int> MapType;
    MapType m;
    vector <int> v;

    // populate map somehow

    for( MapType::iterator it = m.begin(); it != m.end(); ++it ) {
        v.push_back( it->second );
    }
}

如果我要多次使用它,我可能会将其重写为模板函数。就像是:

 template <typename M, typename V>
void MapToVec( const  M & m, V & v ) {
    for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) {
        v.push_back( it->second );
    }
}

原文由 anon 发布,翻译遵循 CC BY-SA 4.0 许可协议

其他答案提到 std::transform ,从语义上讲这是正确的选择。但实际上 std::accumulate 可能更适合这项任务,因为:

  • 它允许将 const 添加到结果向量中;
  • 它只是看起来更好,真正的功能风格。

示例(使用 C++17 语法):

 #include <numeric> // for std::accumulate. Note that it's not in <algorithm> where std::transform is located, thanks to Anton Krug for pointing this out

auto map = std::map<int,bool>{};
map[0]=true;
map[1]=false;

const auto mapValues = std::accumulate(map.begin(), map.end(), std::vector<bool>(map.size()), [](auto& vector, const auto& mapEntry) {
    vector.push_back(mapEntry.second);
    return vector;
});

原文由 Michael D. 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题