Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 删除int和string的简单std映射的完美方法_C++_Arrays_Dictionary - Fatal编程技术网

C++ 删除int和string的简单std映射的完美方法

C++ 删除int和string的简单std映射的完美方法,c++,arrays,dictionary,C++,Arrays,Dictionary,我的std::map看起来像这样 std::map<int, std::string> *myMap = new std::map<int, std::string>[100]; std::map*myMap=newstd::map[100]; 如何删除此项?delete myMap够了吗?既然您已经用new[]分配了100个std::maps,您必须用delete[]解除分配它们: delete[] myMap; 对于每个new/new[],必须有一个delete

我的std::map看起来像这样

std::map<int, std::string> *myMap = new std::map<int, std::string>[100];
std::map*myMap=newstd::map[100];

如何删除此项?
delete myMap
够了吗?

既然您已经用
new[]
分配了100个
std::map
s,您必须用
delete[]
解除分配它们:

delete[] myMap;

对于每个
new
/
new[]
,必须有一个
delete
/
delete[]
(分别)。

boost::scoped\u ptrmyMap=new std::map[100]


强烈建议使用boost::scoped_ptr和boost::shared_ptr(当一个内存位置被多个thigns访问时),它们是智能指针,具有许多优点。它们支持自定义删除器,因此内存安全,这意味着您不必担心删除使用new或new[]创建的内容。它们也是线程安全的。它们的实现是模板化的,并且可以与任何类型等一起工作。

您有一组映射,因此您几乎是正确的。您需要
delete[]myMap
来正确清理数组

但不要那样做。使用地图的
矢量

std::vector<std::map<int, std::string> > myMap(100);
std::vector myMap(100);

这将自动为您管理和清理所有内存

你能说说为什么你试图解决分配
std::map
数组调用的问题吗?关于
std::vector myMaps(100)?如果您使用的是Boost,则需要
作用域数组
,而不是
作用域ptr
,并且需要直接初始化,而不是复制初始化。在现代C++中,<>代码> STD::UngQuyPPTR <代码>(或<代码> STD::向量< /代码>)是可取的。