【发布时间】:2017-04-01 20:55:16
【问题描述】:
对于特定要求,我想要一个带有不同类型键的地图。类似于 boost:any。 (我有一个旧的 gcc 版本)
map<any_type,string> aMap;
//in runtime :
aMap[1] = "aaa";
aMap["myKey"] = "bbb";
使用 boost 可以做到这一点吗?
提前致谢
【问题讨论】:
对于特定要求,我想要一个带有不同类型键的地图。类似于 boost:any。 (我有一个旧的 gcc 版本)
map<any_type,string> aMap;
//in runtime :
aMap[1] = "aaa";
aMap["myKey"] = "bbb";
使用 boost 可以做到这一点吗?
提前致谢
【问题讨论】:
如果您不愿意使用 boost 变体,您可以破解自己的密钥类型。
您可以使用有区别的联合,或者使用一对std::string 和int:
#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
【讨论】:
如果你愿意使用boost::variant:
#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 在这种方法中是不同的键。
【讨论】: