地图中的其他键类型 [英] Different key type in a map

查看:97
本文介绍了地图中的其他键类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于特定要求,我想拥有一个具有不同类型键的映射.类似于boost:any. (我有一个旧的gcc版本)

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";

使用boost可以做到这一点吗?

is this something possible with the use boost ?

先谢谢

推荐答案

如果您不愿意使用boost变体,则可以破解自己的密钥类型.

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

您可以使用有区别的联合,也可以采用低级技术,只需使用一对std::string和int:

You could use a discriminated union, or go low-tech en simply use a pair of std::string and 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

这篇关于地图中的其他键类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆