Different key type in a map

柔情痞子 提交于 2019-12-08 08:17:31

问题


for a particular requirement I want to have a map with keys in different type. Similar to boost:any. (I have an old gcc version)

map<any_type,string> aMap;

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

is this something possible with the use boost ?

thank in advance


回答1:


If you're not willing to use boost variant, you can hack your own key type.

You could use a discriminated union, or go low-tech en simply use a pair of std::string and int:

Live On 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";
}

Prints:

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



回答2:


If you're willing to use boost::variant:

Live On 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";
}

Key ordering/equation is automatically there. Note though that "1" and 1 are different keys in this approach.



来源:https://stackoverflow.com/questions/43161938/different-key-type-in-a-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!