Khaled Hasan Khaled Hasan - 25 days ago 13
C++ Question

Sort maps by value in the specified order of key's priority

I have three maps of integer

std::map<string,int> map1;

map1["ymax"]=10;
map1["ymin"]=16;
map1["xval"]=10;

std::map<string,int> map2;

map2["ymax"]=16;
map2["ymin"]=20;
map2["xval"]=28;

std::map<string,int> map3;

map3["ymax"]=16;
map3["ymin"]=20;
map3["xval"]=10;


and a map contain this maps

std::map<string,std::map<string,int>> almap;

allmap["map1"]=map1;
allmap["map2"]=map2;
allmap["map3"]=map3;


I want to sort the last map as a key
ymin
in the inner map, but if remain equal maps in big map I want to sort as a key
xval
then as key
ymax
, same idea

The right sort to
allmap >> map1,map3,map2

Answer

Create vector of all the maps and sort them by tieing their keys in the order of key's specified priority:

vector<map<string,int>> v{map1, map2, map3};

std::sort(v.begin(), v.end(), [](std::map<string,int> &lhs, std::map<string,int> &rhs){
                                 return tie(lhs["ymax"], lhs["ymin"], lhs["xval"]) < 
                                        tie(rhs["ymax"], rhs["ymin"], rhs["xval"]);}
          );

Live Demo