提问者:小点点

自定义std::将值类型设置为unordered_map


让代码说出来:

auto SetCompare = [](const string& a, const string& b)
{
    size_t L = a.length();
    size_t R = b.length();
    if (L == R) return (a < b);
    return L < R;
};

using MySet = std::set<string, decltype(SetCompare)>;

unordered_map<string, MySet> Map;

插入或访问不起作用:

Map["abc"];
Map["xyz"].insert("mapped to xyz");

// Insert TO set works
MySet mySet(SetCompare); // HINT
mySet.insert("x");
mySet.insert("abc");

// But not to the map!
Map.insert({"pqr", mySet});

在提示的位置,我将setcomparelambda(而不仅仅是type)传递给myset的构造函数。问题是如何将它传递给unordered_map的“值”类型?


共1个答案

匿名用户

似乎C++14(甚至C++17)删除了lambda的默认构造函数。

一种解决方法是自行定义lambda/函数类型:

struct SetCompare {
    
    SetCompare() = default; // let's make the compiler happy!
    
    auto operator()(const string& a, const string& b) const {
        size_t const L = a.length();
        size_t const R = b.length();
        return L == R ? a < b : L < R;
    }
};
    
int main()
{
    using MySet = std::set<string, SetCompare>;
    unordered_map<char, MySet> M;
    M['0'].insert("a");
    return 0;
}

希望能帮上忙。