【问题标题】:How do I destruct a map and populate a map pointer in C++?如何在 C++ 中破坏地图并填充地图指针?
【发布时间】:2016-10-17 10:16:53
【问题描述】:

如果我们创建一个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:在函数“int main()”中: test.cpp:8:14: error: no match for ‘operator=’(操作数类型是 ‘std::map’ 和 ‘int’) 我的地图[1] = 2; ^ 在 /usr/include/c++/5/map:61:0 包含的文件中, 来自 test.cpp:2: /usr/include/c++/5/bits/stl_map.h:296:7: 注意: 候选: 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; _比较 = std::less; _Alloc = std::allocator >] 运算符=(常量映射& __x) ^ /usr/include/c++/5/bits/stl_map.h:296:7:注意:没有已知的参数 1 从“int”到“const std::map&”的转换

如何在 C++ 中破坏 map?它是“可破坏的”吗?

另外,如何初始化/填充 map&lt;&gt; 指针的值?

【问题讨论】:

  • 如果您使用new(*myMap)[1] = 2; 可以解决问题。其余的在下面的 CinCout 答案中
  • 同样的原因int *i = new int(0); i += 5; delete i; 不会在int 上加 5。
  • “如果我们创建一个map&lt;int,int&gt;,我们可以清除它,但它仍然保留在内存中,对吧?”,地图管理对象本身(可能是或两打字节,具体取决于您是在编译 32 位还是 64 位应用程序以及 map 实现是否添加了数据以支持调试)但 map 用于存储的数据元素的内存将被释放由应用程序重用。总而言之,在map 上添加clear 很少值得做。这与 vector 形成鲜明对比,后者往往会挂在曾经存储元素的内存中。
  • 走第一条路线。当您清除地图时,其内容就消失了。它占用的存储空间不会超过指向它的指针(嗯,也许只是一点多一点)。不要让你的代码不必要地复杂化。
  • 你有 15K 代表。您应该知道一次只问一个问题。

标签: c++ pointers initialization destructor stdmap


【解决方案1】:

如何在 C++ 中破坏地图?

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

当声明为指针时,如果使用了newdelete 关键字就可以解决问题。如果使用智能指针,则无需显式调用delete

如何初始化/填充地图指针的值?

使用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。

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

【讨论】:

  • ^这在这种情况下有何影响?
  • 通过省略关键细节,您的回答表明它们是等价的,但它们不是。
【解决方案2】:

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

首先是惯用的clear and minimize(交换),您可以创建一个空的临时地图并将其内容与您的工作地图交换

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2016-02-01
    • 2014-01-23
    相关资源
    最近更新 更多