描述:
使用一个map m; 可以使用对应的函数插入数据,因为map重载了[]运算符,所以可以通过m[key] = value进行赋值。一般情况,value为默认类型啊,直接使用[]运算符直接操作即可。没什么问题。
当value为自定义类,会出现相关问题,例如:
#include #include #include #include using namespace std; class A { public: A(){ cout<<"A()"<<",Line:"<<__LINE__< vm = {{1,A(1,1)}}; cout<<"Start vm"<>所示,或者使用insert_or_assign函数. vm[2] = A(2,2); cout<<"End vm"< map中value是自定义类型的,直接使用[]进行存储结时,例中value的调用自身方法为先调用{默认无参构函数,再调用赋值函数} 所以,如下使用[]存value,必须在student中实现默认构造,不然编译会出错,如下: << 没有默认无参构造函数,直接编译报错失败:(添加默认构造函即可解决该问题) /usr/include/c++/4.8.2/tuple:1090:70: error: no matching function for call to ‘A::A()’ second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...) >> c++17中,解决了该问题,可以直接使用insert_or_assign() vm.insert_or_assign(0,A(0,0)); 2.使用结构体或者类作为map的key是,需要重载运算符<,不然会就报错, /usr/include/c++/5/bits/stl_function.h:387:20: error: no match for ‘operator<’ (operand types are ‘const Person’ and ‘const Person’) { return __x < __y; } 通常使用string直接坐为key,那是因为string重载了运算符<. 正确使用代码: #include #include #include #include using namespace std; class A { public: A(){ cout<<"A()"<<",Line:"<<__LINE__<
map中value是自定义类型的,直接使用[]进行存储结时,例中value的调用自身方法为先调用{默认无参构函数,再调用赋值函数} 所以,如下使用[]存value,必须在student中实现默认构造,不然编译会出错,如下: << 没有默认无参构造函数,直接编译报错失败:(添加默认构造函即可解决该问题) /usr/include/c++/4.8.2/tuple:1090:70: error: no matching function for call to ‘A::A()’ second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...) >> c++17中,解决了该问题,可以直接使用insert_or_assign() vm.insert_or_assign(0,A(0,0));
2.使用结构体或者类作为map的key是,需要重载运算符<,不然会就报错,
/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for ‘operator<’ (operand types are ‘const Person’ and ‘const Person’) { return __x < __y; }
通常使用string直接坐为key,那是因为string重载了运算符<.
正确使用代码:
#include #include #include #include using namespace std; class A { public: A(){ cout<<"A()"<<",Line:"<<__LINE__<
上一篇 c# constructor的使用记录(学习)
下一篇 java数据类型
版权所有 (c)2021-2022 MSHXW.COM
ICP备案号:晋ICP备2021003244-6号