gpt4 book ai didi

c++ - 在 C++ 中更新 map 值

转载 作者:太空狗 更新时间:2023-10-29 21:05:54 24 4
gpt4 key购买 nike

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

关于c++ - 在 C++ 中更新 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8690119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com