映射中的 C++ 结构作为值 - 错误 "no instance of overloaded function matches the argument list"

标签 c++ dictionary

我想将结构用作映射中的值。为什么我必须使用 value_type 向 map 中插入内容?

#include <map>

struct myStruct {};

int main()
{
    std::map<int,myStruct> myStructMap;
    myStruct t;

    myStructMap.insert(std::map<int,myStruct>::value_type(1, t));  // OK

    myStructMap.insert(1,t);
    // Error:
    //   "no instance of overloaded function 'std::map [...]' matches
    //    the argument list"
}

最佳答案

很简单,没有std::map::insert这样的函数将键作为一个参数,将值作为另一个参数。

你应该std::map::insert使用 map 的实际值类型,即 std::pair<const Key, Value> .

当然,C++ 标准库可以为您提供此重载,但它没有理由这样做。

唯一与您尝试执行的操作类似的函数是 C++11 emplace (和 emplace_hint ):

myStructMap.emplace(1,t);

在这个例子中,参数直接转发value_type的构造函数.

关于映射中的 C++ 结构作为值 - 错误 "no instance of overloaded function matches the argument list",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21310285/

相关文章:

c++读取文本文件并将其存储到 vector

c++ - 使用带有字符串定界符的 boost::tokenizer

c++ - 初始化 递增 递减 And 和 or 运算符

c++ - 此代码中没有匹配的调用函数

C++ for循环奇怪的行为

python - 从文本文件创建字典 2 个值

ios - 如何将 plist 的数据包括字典行到字典数组以在代码上使用它

Python3,列表中的元组,如何获取其中的所有值

python - 每个键有多个值的列表到字典转换?

python - PyQt5:如何从字典项列表生成 QTreeView?