【问题标题】:Different key type in a map地图中的不同键类型
【发布时间】:2017-04-01 20:55:16
【问题描述】:

对于特定要求,我想要一个带有不同类型键的地图。类似于 boost:any。 (我有一个旧的 gcc 版本)

map<any_type,string> aMap;

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

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

提前致谢

【问题讨论】:

    标签: c++ boost boost-any


    【解决方案1】:

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

    您可以使用有区别的联合,或者使用一对std::string 和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";
    }
    

    打印:

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

    【讨论】:

    • 非常感谢您提供的线索。探索歧视性工会作为个人进步。
    【解决方案2】:

    如果你愿意使用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";
    }
    

    键排序/方程式自动存在。请注意,尽管"1"1 在这种方法中是不同的键。

    【讨论】:

    • 您好,感谢您的回答。正如我的问题所述,我使用的是旧的编译器,并且要求不要使用 boost。
    • 问题被标记为boost。请求文本说“使用 boost 可以做到这一点吗?”。旧的 gcc 版本可以正常工作。也许你也可以使用旧版本的 boost
    • 也许我应该更准确:)。这是一个遗留系统,无法更改构建环境或依赖项。
    • 我认为这无关紧要。只需决定答案是否回答了问题(确实如此)以及您是否觉得它有帮助。如果您还有其他问题,您将不得不发布一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多