Copy std::map into std::vector of pairs

后端 未结 3 1391
时光取名叫无心
时光取名叫无心 2021-01-17 08:34

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:

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-17 08:43

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

提交回复
热议问题