简体   繁体   English

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

[英]Copy std::map into std::vector of pairs

I'm trying to copy a map into a vector of pair, so I can then sort the vector by the second data member of the pairs. 我正在尝试将地图复制到对的向量中,因此我可以通过对的second数据成员对向量进行排序。 I have resolved this doing like this: 我已经解决了这样做:

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;});
}

I need to find a way to do this without using a raw loop, using the standard library instead. 我需要找到一种方法来实现这一点而不使用原始循环,而是使用标准库。 I have come across a lot of examples doing this by only transferring either the keys or the values of the map. 我通过传递地图的键或值来遇到很多这样的例子。 I need to copy into a vector of pairs<string, int> . 我需要复制到pairs<string, int>的向量中。 What is the best way to do it? 最好的方法是什么?

Just use std::vector 's assign member function. 只需使用std::vectorassign成员函数。

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

If you have existing values in the vector that you don't want overwritten then use insert instead like 如果向量中存在您不想覆盖的值,则使用insert代替

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

You can use std::copy and std::back_inserter : 您可以使用std::copystd::back_inserter

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

Honestly, I think that a range- for loop is clearer: 老实说,我认为range- for循环更清晰:

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

Regardless, you can use std::vector::reserve to preallocate memory on your target vector , avoiding unnecessary reallocations. 无论如何,您可以使用std::vector::reserve来预先分配目标vector上的内存,从而避免不必要的重新分配。

It's worth noting that if you are creating a vector for this purpose , you may use the vector's constructor directly: 值得注意的是,如果要为此目的创建向量 ,可以直接使用向量的构造函数:

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

In C++17, you may also omit the vector's template arguments to have the compiler deduce them: 在C ++ 17中,您也可以省略向量的模板参数,让编译器推导出它们:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM