我想在结构中使用struct作为值.为什么我必须使用value_type在地图中插入一些东西?
#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"
}
Run Code Online (Sandbox Code Playgroud)
很简单,没有这样的功能,std::map::insert即将键作为一个参数,将值作为另一个参数.
您应该std::map::insert使用地图的实际值类型,即std::pair<const Key, Value>.
当然,C++标准库本可以为您提供这种重载,但它没有理由.
C++ 11 emplace(和emplace_hint)是唯一能完成类似于你正在尝试做的事情的函数:
myStructMap.emplace(1,t);
Run Code Online (Sandbox Code Playgroud)
在此示例中,参数直接转发给构造函数value_type.