将std :: map复制到std :: vector中

时间:2018-12-19 15:33:33

标签: c++ stdvector stdmap c++-standard-library std-pair

我正在尝试将地图复制到向量对中,因此可以按照向量对中的second数据成员对向量进行排序。我已经这样解决了:

void mappedWordsListSorter(){
  for (auto itr = mappedWordsList.begin(); itr != mappedWordsList.end(); ++itr){
    vectorWordsList.push_back(*itr);
  }
  sort(vectorWordsList.begin(), vectorWordsList.end(), [=](pair<string, int>& a, pair<string, int>& b){return a.second > b.second;});
}

我需要找到一种方法,而不使用原始循环,而是使用标准库。我遇到了很多仅通过传递键或映射值来执行此操作的示例。我需要复制到pairs<string, int>的向量中。最好的方法是什么?

3 个答案:

答案 0 :(得分:22)

只需使用std::vector的{​​{3}}成员函数。

//no need to call reserve, bidirectional iterators or better will compute the size and reserve internally.
vectorWordsList.assign(mappedWordsList.begin(), mappedWordsList.end());

如果向量中已有要覆盖的值,则使用assign代替

vectorWordsList.reserve(vectorWordsList.size() + mappedWordsList.size()); // make sure we only have a single memory allocation
vectorWordsList.insert(vectorWordsList.end(), mappedWordsList.begin(), mappedWordsList.end());

答案 1 :(得分:7)

您可以使用std::copystd::back_inserter

std::copy(mappedWordsList.begin(), 
          mappedWordsList.end(), 
          std::back_inserter(vectorWordsList));

老实说,我认为范围-for循环更清晰:

for(const auto& kv : mappedWordsList) 
     vectorWordsList.emplace_back(kv);

无论如何,您都可以使用std::vector::reserve在目标vector上预分配内存,避免不必要的重新分配。

答案 2 :(得分:7)

值得注意的是,如果您为此目的创建矢量,则可以直接使用矢量的构造函数:

std::vector<std::pair<FirstType,SecondType>> vectorWordsList( mappedWordsList.begin(), mappedWordsList.end() );

在C ++ 17中,您还可以省略向量的模板参数,以使编译器推导它们:

std::vector vectorWordsList( mappedWordsList.begin(), mappedWordsList.end() );