Flip map key-value pair

前端 未结 4 1034
后悔当初
后悔当初 2021-01-11 17:10

I have a map. I want to flip the key-value so that it not becomes map. So basically the value of the first map becomes the key of the second map. How do i do this?

E

4条回答
  •  旧时难觅i
    2021-01-11 17:33

    #include
    #include
    #include
    
    using namespace std;
    
    template
    pair flip_pair(const pair &p)
    {
        return pair(p.second, p.first);
    }
    
    template
    map flip_map(const map &src)
    {
        map dst;
        transform(src.begin(), src.end(), inserter(dst, dst.begin()), 
                       flip_pair);
        return dst;
    }
    
    int main(void)
    {
      std::map src;
    
      src['a'] = 10;
      src['b'] = 20;
      src['c'] = 160;
      src['d'] = 110;
      src['e'] = 0;
    
      std::map dst = flip_map(src);
    
      map::iterator it;
      for(it=dst.begin(); it!=dst.end(); it++) {
        cout << it->first << " : " << it->second << endl;
      }
    }
    

提交回复
热议问题