简体   繁体   English

如何从向量中删除元素<shared_ptr>

[英]How to erase an element from a vector<shared_ptr>

I´m buiding a sort of a registry class using the following code: 我使用以下代码构建一种注册表类:

class MyClass 
{
    public:
       int a;
       std::string b;
};

class Register
{
    public:
        std::vector<std::shared_ptr<MyClass>> items;

        bool registerItem(std::shared_ptr<MyClass> item)
        {
            /*
             * Check if item exists
             */
            auto position = std::find(items.begin(), items.end(), item);

            if (position != items.end())
                return false;

            items.push_back(item);

            return true;
        }

         bool unregisterItem(std::shared_ptr<MyClass> item)
        {
            auto position = std::find(items.begin(), items.end(), item);

            if (position == items.end())
               return false;

            items.erase(item);

            return true;
        }
};


int main()
{
    std::shared_ptr<MyClass> item1 = new MyClass;

    Register registry;

    if (!registry.registerItem(item1))
        std::cout << "Error registering item1" << std::endl;
    else
        std::cout << "Success registering item1" << std::endl;

    if (!registry.registerItem(item1))
        std::cout << "Error unregistering item1" << std::endl;
    else
        std::cout << "Success unregistering item1" << std::endl;
}

I can´t compile this code, as items.erase(item) complains about error: no matching member function for call to 'erase' . 我无法编译此代码,因为items.erase(item)抱怨error: no matching member function for call to 'erase'

Why I can´t erase the object I´ve added. 为什么我无法擦除添加的对象。 What is the correct way to remove a std::shared_ptr from a std::vector ? std::vector删除std::shared_ptr的正确方法是什么?

因为要在items使用迭代器( position ),所以:

items.erase(position);

There are two declarations available. 有两个可用的声明。 From cppreference : 来自cppreference

iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);

You try to std::vector::erase the item itsself instead of the iterator. 您尝试std::vector::erase项目本身而不是迭代器。 Use 采用

items.erase(position);

instead. 代替。

You have to call erase on position , not item 您必须在position而不是item上调用erase
since erase is used on iterators 因为在迭代器上使用了擦除

You should pass to erase iterator not a value, there is nothing special with deleting std::shared_ptr. 您应该传递擦除迭代器而不是值,删除std :: shared_ptr并没有什么特别的。 Also you have mistype in code: you register item twice instead of unregister it in the second call. 另外,您在代码中输入的内容有误:您注册了两次,而不是在第二次调用中取消注册。

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

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