如何擦除包含结构的地图 包含结构的地图
How do I erase a map containing structures of maps which contain structures?
我有以下代码用于创建一个包含结构的映射,其中包含一个包含结构映射的结构。 我的问题是如何从提供程序Map中删除元素而不会留下任何内存泄漏。 我可以只做一个providerMap[prov_id].erase()还是我需要在第二个或更复杂的东西上做一个删除?
struct uriPrivs {
std::string name;
uchar properties;
};
struct providerValues {
int KeepAlive;
std::map<std::string /*uri*/, uriPrivs> uris;
};
std::map<std::string /*prov_id*/, providerValues> providerMap;
RISStorageManager::risStorageResponse RISStorageManager::update_provider(const std::string &prov_id, int KeepAlive) {
if (providerMap.find(prov_id) == providerMap.end()) {
providerValues x;
x.KeepAlive = KeepAlive;
providerMap[prov_id] = x;
return risStorageCreated;
} else {
providerMap[prov_id].KeepAlive = KeepAlive;
return risStorageUpdated;
}
}
RISStorageManager::risStorageResponse RISStorageManager::update_uri(const std::string &prov_id, std::map<std::string, uriPrivs> &uris) {
providerMap[prov_id].uris = uris;
}
如前所述,您不需要在此处显式释放任何内存。你自己不是"新"任何东西。一切都将由映射对象的析构函数处理。
你可以稍微压缩一下update_provider函数...
RISStorageManager::risStorageResponse update_provider(const std::string &prov_id, int KeepAlive)
{
RISStorageManager::risStorageResponse response = (providerMap.end() == providerMap.find(prov_id)) ?
risStorageCreated : risStorageUpdated;
providerMap[prov_id].KeepAlive = KeepAlive;
return response;
}
这里有一些测试代码来解释几件事......
int main(int argc, char *argv [])
{
// Create new provider and print result...
std::cout << update_provider("test1", 1) << std::endl;
// Add a URI to the first provider for fun...
providerMap["test1"].uris["www.google.com"].name = "GOOGLE";
providerMap["test1"].uris["www.google.com"].properties = 0xFF;
// Create new provider and print result...
std::cout << update_provider("test2", 1) << std::endl;
// Create new provider and print result...
std::cout << update_provider("test3", 1) << std::endl;
// Update first provider and print result...
std::cout << update_provider("test1", 0) << std::endl;
// Explicitly remove first provider if you want...
providerMap.erase("test1");
//
// Now only 2 providers are in map (test2 and test3).
// The program will exit and the STL map destructors will take care of any
// memory deallocation that is needed to clean up the maps. You don't need
// to explicitly clean up anything unless you want to remove providers from
// your map explicitly.
//
return 0;
}
相关文章:
- 结构包含在两个头文件中,这两个文件我都不拥有
- 包含矢量指针的结构的内存释放问题
- 包含 std::list 的结构体的 C++ 初始化
- 不能在其他文件中包含结构
- 使用包含结构的数组的成员函数
- 删除包含结构的向量的向量
- 如何声明包含结构的类的成员函数
- C++包含结构的结构 SIGSEGV
- 复制包含结构的向量
- 我们如何在 c++ 实现文件中包含结构
- 类,其中包含结构.C++
- 反转指向成员的指针(即获取包含结构的地址)
- 编译包含结构的h文件时发生链接错误
- 如何擦除包含结构的地图 包含结构的地图
- 包含结构的向量的向量
- 使用Vector包含结构的指针问题
- 对包含结构的deque进行排序
- java c++传递一个包含c++结构的向量的向量
- 向量包含结构的排序
- 返回包含结构