映射中的c ++ struct作为值 - 错误"没有重载函数的实例与参数列表匹配"

Seb*_*itz 0 c++ map

我想在结构中使用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)

Lig*_*ica 7

很简单,没有这样的功能,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.

  • @CouchDeveloper:它不应该编译,但不能保证它不会; 例如,如果存在从"int"到"const_iterator"的非标准转换. (3认同)
  • @SebastianSchmitz:给我打电话给你的同事.:) (2认同)