Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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?

like image 340
Victor Avatar asked Dec 19 '18 15:12

Victor


People also ask

Can we make vector of map in C++?

Map in STL: Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.

Can we use vector as a key in map?

In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.


2 Answers

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());
like image 92
NathanOliver Avatar answered Sep 18 '22 13:09

NathanOliver


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() );
like image 22
Drew Dormann Avatar answered Sep 21 '22 13:09

Drew Dormann