C++ 可以将boost.any用作std::map(或类似的东西)中的键吗?
C++ 可以将boost.any用作std::map(或类似的东西)中的键吗?,c++,boost,C++,Boost,std::map不起作用,所以我想知道是否有其他方法 是否有任意键?我认为问题不在于Boost::Any,而在于您没有指定自定义比较器。由于map是一个排序关联容器,因此需要有一个比较器 以下内容适合我:根据您的目的定制: #include <iostream> #include <map> #include <boost/any.hpp> using namespace std; struct cmp { bool operator()(c
std::map
不起作用,所以我想知道是否有其他方法
是否有任意键?我认为问题不在于
Boost::Any
,而在于您没有指定自定义比较器。由于map
是一个排序关联容器,因此需要有一个比较器
以下内容适合我:根据您的目的定制:
#include <iostream>
#include <map>
#include <boost/any.hpp>
using namespace std;
struct cmp {
bool operator()(const boost::any& l, const boost::any& r) {
try
{
int left = boost::any_cast<int>(l);
int right = boost::any_cast<int>(r);
return left < right;
}
catch(const boost::bad_any_cast &)
{
return false;
}
return false;
}
};
int main() {
map<boost::any, string, cmp> ma;
boost::any to_append = 42;
ma.insert(std::make_pair(to_append, "int"));
if (ma.find(42) != ma.end()) {
cout << "hurray!\n";
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
结构cmp{
bool运算符()(常量boost::any&l,常量boost::any&r){
尝试
{
int left=boost::任意_cast(l);
int right=boost::任意_cast(r);
返回左<右;
}
捕获(常量增强::坏的\u任何\u投射&)
{
返回false;
}
返回false;
}
};
int main(){
map ma;
boost::any to_append=42;
插入(std::make_pair(to_append,“int”);
如果(ma.find(42)!=ma.end()){
cout您可能希望查看boost::variant
而不是boost::any
,因此您可以确保所使用的所有类型都是可比较的
使用Visitor将是为variant
s提供比较运算符的最佳方法。如果使用(any.type()==other.type())我如何在stackoverflow中发布templateparameters?您的比较函子在映射中使用无效,因为对于某些(a,b),它可以为a