简体   繁体   English

从QMap中删除指针?

[英]Delete a pointer from QMap?

I've got a QMap with the QString key and with value pointer to an Object of myclass. 我有一个带QString键的QMap和一个指向myclass对象的值指针。 But I don't know how to delete a pointer from QMap when I allocate the value of QMap dynamically: 但我不知道如何删除QMAP 指针 ,当我动态分配QMAP的价值:

QMap<QString, myClass*> types;

myClass *type = types.value(typeKey);
    if (!type) {
        type = new myClass;
        types.insert(typeKey, type);

How shall I delete a pointer by a key? 如何通过键删除指针? I'm aware of QMap methods like remove . 我知道像remove这样的QMap方法。 Is that safe to use? 这样安全吗?

What about the following: 以下内容如何:

const QString key = types.key(static_cast<myClass*>());
    types.remove(key);

The remove() function removes the item from the map, however it does not delete it, so you have to do it yourself, if it is a pointer to the object. remove()函数从地图中删除该项,但它不会删除它,因此如果它是指向对象的指针,则必须自己执行。 I would do that in the following way: 我会用以下方式做到这一点:

myClass *type = types.take("foo");
delete type;

As QMap::clear doesn't delete pointers, there is another way of doing it with qDeleteAll function. 由于QMap :: clear不会删除指针,因此还有另一种方法可以使用qDeleteAll函数。 qDeleteAll works on values only in case of QMap and QHash and not on keys even those are of pointer type, so below example will work only on values of kay-value container. qDeleteAll仅在QMap和QHash的情况下处理值,而不是键,即使是指针类型的键,因此下面的示例仅适用于kay值容器的值。 In this value must be of pointer type. 在此值必须是指针类型。

QMap<int,Employee *> mlist;
mlist.insert(1,new Employee("Blackpool", "Stephen"));
mlist.insert(2,new Employee("Twist", "Oliver"));

qDeleteAll(mlist);
#or you can do it like
qDeleteAll(mlist.begin(),mlist.end());

update: and yes always use clear() after it, to remove the entries from maps eg mlist.clear(); 更新:是的,总是在它之后使用clear(),从地图中删除条目,例如mlist.clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM