在c++中向映射中插入复杂值

Inserting complex values to a map in C++

本文关键字:复杂 插入 c++ 映射      更新时间:2023-10-16

我有麻烦插入数据到这个地图。老实说,我不知道如何做到这一点,但我给出的最后一行代码是我需要修复的部分。

map<string, vector<vector<Obj*>* >* > the_map;
vector<vector<Obj*> *>*  vectors = new vector<vector<Obj*> *>;
vector<Obj*> Obj_vector;
vectors->push_back(&Obj_vector);                                                    
the_map.insert(make_pair(string("field1", &vectors)); //error on this line only

试试这个:

 the_map.insert(make_pair(string("field1"),  vectors)); 
                       //you forgot this ^  ^
                       //                   |
                       //                   & is not needed here 
顺便说一下,我怀疑你的代码中使用了这么多指针,尤其是这两行:
vector<Obj*> Obj_vector;  //this is local variable
vectors->push_back(&Obj_vector); //inserting address of the local variable

地址插入到vector中?

注意局部变量在超出作用域后将不存在,这反过来意味着您刚刚插入到vector中的地址指向被销毁的对象,并且使用它将调用未定义的行为。