如何擦除包含结构的地图 包含结构的地图

How do I erase a map containing structures of maps which contain structures?

本文关键字:包含 结构 地图 擦除 何擦除      更新时间:2023-10-16

我有以下代码用于创建一个包含结构的映射,其中包含一个包含结构映射的结构。 我的问题是如何从提供程序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;
}