如何在 C++ 中销毁地图并填充地图指针?

How do I destruct a map and populate a map pointer in C++?

如果我们创建一个map<int,int>,我们可以清除它但它仍然留在内存中,对吗?例如

#include <map>
using namespace std;

int main(){

    map<int,int> myMap;
    myMap[1] = 2;
    myMap.clear();

return 0;
}

但是如果我们设置一个指针而不是实际的 map,我可以用 delete 破坏它,但我不能用同样的方式填充地图:

#include <map>
using namespace std;

int main(){

    map<int,int> *myMap = new map<int,int>;
    // myMap[1] = 2;
    delete myMap;

return 0;
}

取消注释 myMap[1] = 2; 行以错误结束:

alvas@ubi:~$ g++ test.cpp test.cpp: In function ‘int main()’: test.cpp:8:14: error: no match for ‘operator=’ (operand types are ‘std::map’ and ‘int’) myMap[1] = 2; ^ In file included from /usr/include/c++/5/map:61:0, from test.cpp:2: /usr/include/c++/5/bits/stl_map.h:296:7: note: candidate: std::map<_Key, _Tp, _Compare, _Alloc>& std::map<_Key, _Tp, _Compare, _Alloc>::operator=(const std::map<_Key, _Tp, _Compare, _Alloc>&) [with _Key = int; _Tp = int; _Compare = std::less; _Alloc = std::allocator >] operator=(const map& __x) ^ /usr/include/c++/5/bits/stl_map.h:296:7: note: no known conversion for argument 1 from ‘int’ to ‘const std::map&’

如何在 C++ 中销毁 map?是"destructable"吗?

此外,我如何 initialize/populate map<> 指针的值?

How do I destruct a map in C++?

当您将它声明为一个对象时(第一种情况),它会在超出范围时被销毁。

当声明为指针时,如果使用 newdelete 关键字就可以实现。如果使用智能指针,则无需显式调用 delete.

How do I initialize/populate the values of a map<> pointer?

使用insert()方法,像这样:

#include <map>
using namespace std;

int main(){

    map<int,int> *myMap = new map<int,int>;
    myMap->insert(make_pair<int, int>(1, 2));
    delete myMap;

return 0;
}

或者,按照@Michael 的建议,您可以使用 (*myMap)[1] = 2; 但我更喜欢使用 API。

注意:正如评论中所指出的,operator[]insert() 对于 std::map 在行为方面并不相似。只是,在这个最小的例子中,它们没有反映出任何区别。

有几种方法可以释放 std::map 正在使用的内存(至其初始最小值),而无需求助于指针。

首先是惯用的清除和最小化(交换),您可以创建一个空的临时地图并交换其内容与您的工作地图:

std::map<int,int>().swap(myMap); // memory reset to minimum

另一种方法是使用内部范围 {}.

来控制地图的范围
int func()
{
    { // <- start an internal scope for the map

        std::map<int,int> myMap;

        // use the map

    } // <- let the map go out of scope when done using it

    // carry on without the map
}

如果你必须使用一个指针(最好避免)那么你需要取消引用使用*的指针像这样:

(*myMap)[key] = value;