c++ - std::map <std::any,std::any>麻烦

标签 c++ visual-studio stdmap

我正在尝试使用std:map类型的键和值制作std::any
Visual Studio 2017

std::map<std::any, std::any> m("lastname", "Ivanov");
std::cout << std::any_cast<std::string>(m["lastname"]) << std::endl;

给我一个

error: binary '<' : no operator found which takes a left-hand operand of type 'const_Ty'

最佳答案

std::any没有二进制“<”运算符(小于)。如何“索引” std::map元素的默认方法。

解决方案可能包括:

  • 使用另一个键(具有运算符“<”)
  • 使用自定义比较器,例如:
    #include <map>
    #include <any>
    
    int main() {
        auto elements = std::initializer_list<std::pair<const std::any, std::any>>{};
        auto mymap = std::map(elements, [](const std::any& lhs, const std::any& rhs){return false;});
    }
    

  • 然后实现比较功能,而不是返回false

    try it yourself

    关于c++ - std::map <std::any,std::any>麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58058719/

    相关文章:

    c++ - QRegExp 不符合预期

    .net - 找不到Microsoft.VisualStudio.TextTemplating程序集

    json - json 文档中的成员名称中出现意外的字符序列

    c++ - 使用 const char * literal 作为 std::map 键是否安全?

    c++ - 为什么这个噪声函数不处理否定参数?

    c++ - 我们如何确定函数应该包含在哪个类中

    c++ - 将依赖列表(需求)与 conanfile.py 分开

    c++ - Armadillo 读MAT文件报错

    c++ - 删除元素时 map 迭代器如何失效?

    c++ - std::map with key as templated structs with enum member