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

你说的曾经没有我的故事 提交于 2019-12-01 15:46:07

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

You can use std::copy and std::back_inserter:

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

Honestly, I think that a range-for loop is clearer:

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.

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:

std::vector vectorWordsList( mappedWordsList.begin(), mappedWordsList.end() );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!