将std :: map复制到std :: vector中 [英] Copy std::map into std::vector of pairs
问题描述
我正在尝试将地图复制到向量对中,因此可以根据向量对中的 second
数据成员对向量进行排序.我已经这样解决了:
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. 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;});
}
我需要找到一种方法,而不使用原始循环,而是使用标准库.我遇到了很多仅通过传递键或映射值来执行此操作的示例.我需要复制到 pairs< string,int>
的向量中.最好的方法是什么?
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>
. What is the best way to do it?
推荐答案
Just use std::vector
's assign
member function.
//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
vectorWordsList.reserve(vectorWordsList.size() + mappedWordsList.size()); // make sure we only have a single memory allocation
vectorWordsList.insert(vectorWordsList.end(), mappedWordsList.begin(), mappedWordsList.end());
这篇关于将std :: map复制到std :: vector中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!