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

Time:12-04

my code copies the map in the same order

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

I want this instead

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

CodePudding user response:

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.

  • Related