Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swap map values to a multimap

Tags:

c++

containers

I store some key-values with a map, then I need to sort them by values, I am temped to use the following:

#include <iostream>
#include <map>
#include <string>

int main ()
{
    std::map<std::string, int> map1;
    std::multimap<int, std::string> multimap2;

    map1.insert ( std::pair<std::string, int>( "one", 4) );
    map1.insert ( std::pair<std::string, int>( "two", 2) );
    map1.insert ( std::pair<std::string, int>( "three", 2) );
    map1.insert ( std::pair<std::string, int>( "four", 1) );

    for (auto it = map1.begin(); it != map1.end(); ){
        multimap2.insert(std::pair<int, std::string>( it->second, it->first));
        map1.erase(it++);
    }

   for (auto it = multimap2.rbegin(); it != multimap2.rend(); ++it)
   std::cout << it->first << " --- " << it->second << '\n';

   return 0;
}

that gives me:

4 --- one 2 --- two 2 --- three 1 --- four

as I need, yet...is there a smarter and more efficient way to obtain the same result? It will have to work with a rather large dataset...

Thanks for your time :)

like image 357
Xarylem Avatar asked Feb 26 '26 22:02

Xarylem


1 Answers

An alternative is to dump them into a vector, and sort that:

typedef std::pair<std::string, int> pair;
std::vector<pair> v;
v.reserve(map1.size());
std::copy(map1.begin(), map1.end(), std::back_inserter(v));
std::sort(v.begin(), v.end(), 
    [](pair const & a, pair const & b) {
        return a.second < b.second;
    });

This will probably be faster than inserting into a multimap, since it only needs one memory allocation.

like image 179
Mike Seymour Avatar answered Feb 28 '26 14:02

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!