1

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

map<any_type,string> aMap;

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

使用 boost 有可能吗?

预先感谢

4

2 回答 2

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是此方法中的不同键。

于 2017-04-01T21:05:23.197 回答
2

如果您不愿意使用 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
于 2017-04-03T13:23:35.547 回答