Home > OS >  How can I reverse loop over a map by value?
How can I reverse loop over a map by value?

Time:02-26

I need to get the pairs of the map sorted by its values, i wonder if it is posible without an temporal declaration. I know i can sort it if i make another map with the keys and values swaped, but i am searching for a better solution. I can't sort the elements afterwards because i only need extract the chars and put them on an array for example.

std::map<char,int> list = {{'A',4},{'V',2},{'N',1},{'J',5},{'G',3}};

for(/* code here */){
 std::cout << /* code here */ << std::endl;
}

Desired outout:

J 5
A 4
G 3
V 2
N 1

CodePudding user response:

This cannot be done with std::map.

This template has an optional template argument which allows for a custom sorting, but this sorting can only be done on the map's key:

template<
   class Key,
   class T,
   class Compare = std::less<Key>,
   class Allocator = std::allocator<std::pair<const Key, T> >
> class map;

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare.

This choice has been done as to not impose the map's value to be an orderable type.


As an alternative, you can use type std::vector<std::pair<char, int>> in combination with std::sort.

#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<std::pair<char,int>> list = {{'A',4},{'V',2},{'N',1},{'J',5},{'G',3}};
    std::sort(begin(list), end(list), [](auto lhs, auto rhs) {
        return lhs.second > rhs.second ? true : ( rhs.first > rhs.first );
    });
    
    for(auto const& pair : list) {
        std::cout << pair.first << ", " << pair.second << '\n';
    }
}

J, 5
A, 4
G, 3
V, 2
N, 1

Live demo

CodePudding user response:

The most appropriate solution depends on HOW are you going to use that list. Is it created once and queried once? Then anything will do: you can just sort the output.

However, if this is a "live" list that is constantly updated, and you need to query it frequently, I would suggest to keep another map of values to vector of keys. Then you would be able to get your result instantly. At a cost of more expensive insertion, of course.

  • Related