在c++中更新映射值

Updating map values in c++

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

这里有一个新问题:我如何让存储在Maptest[2]中的值与变量一起更新?我以为你可以用指针来做,但这不起作用:

map<int, int*> MapTest; //create a map
    int x = 7; 
   //this part gives an error: 
   //"Indirection requires pointer operand ("int" invalid)"
    MapTest[2] = *x; 

    cout << MapTest[2]<<endl; //should print out 7...
    x = 10;
    cout <<MapTest[2]<<endl; //should print out 10...

我做错了什么?

您需要 x地址。您当前的代码正试图解引用一个整数。

MapTest[2] = &x;

然后需要解引用MapTest[2]返回的内容。

cout << *MapTest[2]<<endl;

试试这个:

MapTest[2] = &x; 

您希望将x的地址存储在int*中。不是对x的解引用,它将是内存位置0x7的值,这将是无效的

这里至少有两个问题:

int x = 7;
*x; // dereferences a pointer and x is not a pointer.
m[2] = x; // tries to assign an int value to a pointer-to-int value
// right
m[2] = &x; // & returns the address of a value

现在你又有新问题了。x具有自动寿命,它将是在其周边范围结束时被摧毁。你需要分配它从自由存储区(即堆)。

int* x = new int(7);
m[2] = x; // works assigns pointer-to-int value to a pointer-to-int value

现在你必须记住delete之前map中的每个元素它超出了作用域,否则就会泄漏内存。

map中存储值是更明智的,或者如果你真的需要的话存储一个合适的智能指针(shared_ptrunique_ptr)。

打印:

m[2]; // returns pointer value
*m[2]; // dereferences said pointer value and gives you the value that is being pointed to