这里有新问题:
如何将存储在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;

08-16 09:34