在c++中更新映射值
Updating map values in c++
这里有一个新问题:我如何让存储在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_ptr
或unique_ptr
)。
打印:
m[2]; // returns pointer value
*m[2]; // dereferences said pointer value and gives you the value that is being pointed to
相关文章:
- 从C++本机插件更新Vector3数组
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 为什么 c++ 映射值不针对同一键更新?
- C++ STL 映射同时更新所有值
- 两个进程之间的共享映射内存在编辑时未更新
- 如何使用密钥 2 更新 STL 映射键 1 并将值复制到键 2 中
- 将项目"更新插入"到映射<键、shared_ptr的正确方法<foo>>
- 如何更新映射C++中元素的值
- 通过引用将 std::map 传递给不更新映射的类的构造函数
- 更新标准::映射对象数据
- 在C++11中的每个循环迭代之后更新映射
- 在c++中更新映射值
- 通过删除一些键和一些元素来更新映射的问题
- 如何更新map
>类型的映射 - 如何在C++中更新映射的对象
- 检查映射中是否存在关键字,然后更新值