Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to copy a map <string, int> into a vector <int, string>

my code copies the map in the same order

map <string, int> to vector <string, int>

I want this instead

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

map <string, int> to vector <int, string>

is it possible with std copy?

#include <iostream>
#include <vector>
#include <map>
#include <iterator>
#include <fstream>
using namespace std;

int main(){
  
  fstream fs; 
  fs.open("test_text.txt"); 
  if(!fs.is_open()){
    cout << "could not open file" << endl; 
  }

  map <string, int> mp; 
  string word; 
  while(fs >> word){

    for(int i = 0; i < word.length(); i++){
      if(ispunct(word[i])){
        word.erase(i--, 1);
      }
    }

    if(mp.find(word) != mp.end()){
      mp[word]++; 
    }
  }

  vector <pair <string, int> > v(mp.size()); 
  copy(mp.begin(), mp.end(), v.begin()); 
 
  


  return 0; 
}

>Solution :

Lots of different ways, but this will work

vector<pair<int, string>> v;
v.reserve(mp.size());
for (const auto& p : mp)
    v.emplace_back(p.second, p.first);

Does’t seem to be possible with std::copy since your value types are different and the source is not convertible to the destination. It should be possible with std::transform.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading