簡體   English   中英

地圖中的其他按鍵類型

[英]Different key type in a map

對於特定的要求,我想使用不同類型的鍵的映射。 類似於boost:any。 (我有一個舊的gcc版本)

map<any_type,string> aMap;

//in runtime :
aMap[1] = "aaa";
aMap["myKey"] = "bbb";

使用提升有可能嗎?

預先感謝

如果您願意使用boost::variant

生活在Coliru

#include <boost/variant.hpp>
#include <iostream>
#include <map>

using Key = boost::variant<int, std::string>;
using Map = std::map<Key, std::string>;

int main()
{
    Map m;

    m[1] = "aaa";
    m["myKey"] = "bbb";
}

按鍵排序/等式自動出現。 請注意,盡管"1"1是此方法中的不同鍵。

如果您不願意使用boost變體,則可以破解自己的密鑰類型。

您可以使用有區別的聯合,或者采用低級技術,只需使用一對std::string和int:

生活在Coliru

#include <map>
#include <tuple>
#include <iostream>

struct Key : std::pair<int, std::string> {
    using base = std::pair<int, std::string>;
    Key(int i) : base(i, "") {}
    Key(char const* s) : base(0, s) {}
    Key(std::string const& s) : base(0, s) {}

    operator int() const         { return base::first; }
    operator std::string() const { return base::second; }
    friend bool operator< (Key const& a, Key const& b) { return std::tie(a.first, a.second) <  std::tie(b.first, b.second); }
    friend bool operator==(Key const& a, Key const& b) { return std::tie(a.first, a.second) == std::tie(b.first, b.second); }
    friend std::ostream& operator<<(std::ostream& os, Key const& k) {
        return os << "(" << k.first << ",'" << k.second << "')";
    }
};

using Map = std::map<Key, std::string>;

int main()
{
    Map m;

    m[1] = "aaa";
    m["myKey"] = "bbb";

    for (auto& pair : m)
        std::cout << pair.first << " -> " << pair.second << "\n";
}

印刷品:

(0,'myKey') -> bbb
(1,'') -> aaa

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM