我想将结构用作映射中的值。为什么我必须使用 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/