简体   繁体   English

如何复制 map<string, int> 成一个向量<int, string></int,></string,>

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

my code copies the map in the same order我的代码以相同的顺序复制 map

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

I want this instead我想要这个

map <string, int> to vector <int, string> map <string, int> 到 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; 
}

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. std::copy似乎不可能,因为您的值类型不同并且源不可转换为目标。 It should be possible with std::transform . std::transform应该是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM