2016-11-15 69 views
1

我有整數排序映射在關鍵的優先級的指定順序

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; 

的三張地圖和地圖包含此映射

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

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

我想最後的地圖作爲重點排序ymin在內的地圖,但如果留在大地圖等地圖我要排序的一個關鍵xval那麼作爲關鍵ymax,同樣的想法

正確的類來allmap >> map1,map3,map2

+0

'如果仍然等於地圖'如果什麼等於地圖? –

回答

0

所有地圖的創建載體,通過tie荷蘭國際集團鑰匙在關鍵的規定的優先權的順序進行排序:

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

0

對於教育的目的...

std::map要求在鍵/值對,關鍵是不變的。它還要求密鑰充分描述了順序。

allmap的情況下,提供的密鑰爲std::string,即使具有複雜的自定義比較函數,該地圖也必須繼續。

爲了允許任何類型的排序,我們需要將外部名稱和它們所代表的地圖一起滾動到一個關鍵對象中,並對其進行排序。

這開始主張要麼使用一組對象(因爲現在沒有關聯的數據),要麼保留一個單獨的,排序的按鍵索引,按照我們的自定義謂詞進行排序。

這裏是後者:

#include <string> 
#include <map> 
#include <set> 
#include <vector> 
#include <utility> 
#include <algorithm> 

struct by_keys 
{ 
    template<class...Keys> 
    by_keys(std::map<std::string, std::map<std::string, int>> const& allmap, Keys&&...keys) 
    : keys_ { std::forward<Keys>(keys)... } 
    , allmap_(allmap) 
    { 
    } 

    bool operator()(const std::string& ls, const std::string& rs) const 
    { 
    auto& l = allmap_.find(ls)->second; 
    auto& r = allmap_.find(rs)->second; 
    for (auto& key : keys_) 
    { 
     auto const& il = l.find(key); 
     auto const& ir = r.find(key); 
     if (il == std::end(l) && ir == std::end(r)) return false; 
     if (il == std::end(l) && ir != std::end(r)) return true; 
     if (il != std::end(l) && ir == std::end(r)) return false; 
     if (*il < *ir) return true; 
     if (*ir < *il) return false; 
    } 
    return false; 
    } 

    std::vector<std::string> keys_; 
    std::map<std::string, std::map<std::string, int>> const& allmap_; 
}; 

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

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

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

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

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

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

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

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

    // ok, now lets make an index into this map 

    std::vector<std::string> sorted_keys; 
    for (auto& entry : allmap) { sorted_keys.push_back(entry.first); } 
    std::sort(std::begin(sorted_keys), std::end(sorted_keys), 
      by_keys(allmap, "ymin", "xval", "ymax")); 

    // sorted_keys should now contain the names "map1", "map3", "map2" 
}