簡體   English   中英

向量指針的刪除條目靜態映射C ++

[英]Deletion entries static map of vector pointers c++

我有一個矢量指針的靜態映射:

static std::map<type, std::vector<object *> > m_objects;

在這種情況下應如何刪除條目?

如果m_objects擁有std::vector指向的object s,則必須在std::vector中的每個object上調用delete ,或者使用智能指針,當std::vector被破壞時,該object將自動刪除object s(在這種情況下,將其從map刪除時):

static std::map<type, std::vector<std::unique_ptr<object>>> m_objects;

如果object s不屬於m_object則不能調用delete (因為它們在其他地方使用)。


請參閱可用的C ++智能指針實現?

遍歷映射中的每個條目,對於每個條目,遍歷向量中的每個條目並刪除它們。

for (auto it : m_objects) {
    for (auto ptr : it.second) {
      delete ptr;
    }
}

更好的解決方案可能是使用std::unique_ptrstd::shared_ptr

更好的解決方案是不使用原始指針向量,並利用C ++ 11完美轉發

#include <iostream>
#include <map>
#include <memory>
#include <vector>
using namespace std;

struct object {
};

enum type {
    TYPE0,
    TYPE1
};

typedef std::map<type, std::vector<std::unique_ptr<object> > > long_type;
static long_type m_objects;

int main() {

    std::vector<std::unique_ptr<object>> vec;
    vec.push_back(std::move(std::unique_ptr<object>(new object))); // make_unique in C++14

    m_objects.insert(std::pair<type, std::vector<std::unique_ptr<object>>>(TYPE0, std::move(vec)));

    long_type::iterator it = m_objects.find(TYPE0);

    m_objects.erase(it);

    cout << m_objects.size(); // 0

    return 0;
}

http://ideone.com/5L4g1x

這樣,您不必擔心在每個分配的對象上調用delete (映射將不會單獨執行此操作)。

從插入和刪除元素開始,同一元素代表具有插入擦除功能的普通std::map

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM