是否可以将boost.any用作std :: map中的键(或类似的东西)?

DaV*_*nci 2 c++ boost

std::map<any, string> 没有工作所以我想知道是否有另一种方法来获得arbritary键?

dir*_*tly 5

我认为问题不在于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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您的比较仿函数无法在地图中使用,因为对于某些(a,b)对,<b和b <a都可以返回false. (2认同)