c++ - 如何在 C++ 中更新 map 的对象

标签 c++ c++11

我有一张 map ,里面有一堆整数、 vector 和一张 map 。

class testMap
{
    int var1;
    int var2;
    ........
    .......
    int var50; //variables up to 50
    map  objmap;
    int *ptr
    vector<myClass> vecObj; //vector of myClass objects
}
typedef std::map<string , testMap> eeMap; //global map
eeMap tMap;

假设我使用 map 插入创建了一个条目 tMap.insert(make_pair ("test", *ptrTestMap ) );如何通过函数更新此全局 map 中的对象。

这个新对象可能只更改了一个变量,也可以是多个变量。

void UpdateTestMap(testMap newTestMapValue,string key)
{

//在此输入代码

}

Option#1: Have a overloaded assignment operator 
Option#2 Compare the members one by one and overwrite the variables that are changed.
Option#3 Erase the key and insert it again with the same key and the new object.
##Any other option

我明白这样做的最佳选择是什么?

最佳答案

在这段代码中,“tMap”是一个类型而不是一个实例。您不能使用“tMap.insert”进行添加。 首先像这样声明全局 map :

tMap globalMap;

然后添加值:

globalMap.insert(make_pair ("test", *ptrTestMap ) );

并使用 [] std::map 运算符简单地更改值:

globalMap[key] = newMapValue;

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

相关文章:

c++ - sscanf 多个输入

c++ - 如何找到包含所有给定框的框?

c++ - 有错误的程序还能编译吗?

c++ - 使用 thrust::for_each() 调用实现 CUDA 流时访问结构的结果

c++ - 编写可以从 C++ 使用的 C 头文件

c++ - std::unordered_map 的函数指针

C++ do while not looping

c++ - 线程安全,在C++中有序映射/哈希?

c++ - std::bind 与 std::less_equal

c++ - 使用 Google 测试框架(不是 Windows)进行内存泄漏检测的标准做法是什么