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

Vic*_*tor 17 c++ stdmap stdvector 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;});
}
Run Code Online (Sandbox Code Playgroud)

我需要找到一种方法来实现这一点而不使用原始循环,而是使用标准库.我通过传递地图的键或值来遇到很多例子.我需要复制到一个矢量pairs<string, int>.最好的方法是什么?

Nat*_*ica 22

只要使用std::vectorassign成员函数.

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

如果向量中存在您不想覆盖的现有值,则使用insert相反的方法

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

  • @FrançoisAndrieux如果您通过随机访问迭代器,很可能会因为`map`具有双向迭代器而需要遍历以知道有多少元素要分配空间,因此它不会这样做. (10认同)

Vit*_*meo 7

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

std::copy(mappedWordsList.begin(), 
          mappedWordsList.end(), 
          std::back_inserter(vectorWordsList));
Run Code Online (Sandbox Code Playgroud)

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

for(const auto& kv : mappedWordsList) 
     vectorWordsList.emplace_back(kv);
Run Code Online (Sandbox Code Playgroud)

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


Dre*_*ann 7

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

std::vector<std::pair<FirstType,SecondType>> vectorWordsList( mappedWordsList.begin(), mappedWordsList.end() );
Run Code Online (Sandbox Code Playgroud)

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

std::vector vectorWordsList( mappedWordsList.begin(), mappedWordsList.end() );
Run Code Online (Sandbox Code Playgroud)