删除指针的STL向量条目的快速方法 [英] fast way to delete entries of STL vector of pointers

查看:65
本文介绍了删除指针的STL向量条目的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要删除的指针向量,但是在向量上进行迭代并为每个元素调用delete相当慢.有没有更快的方法?

I have a vector of pointers which I want to delete, but iterating over the vector and calling delete for each element is quite slow. Is there a faster way?

不幸的是,因为我使用了虚拟超类,所以我确实需要存储指针.简化后,类结构看起来像这样:

Unfortunately I really need to store pointers, since I use a virtual superclass. Simplified, the class structure looks something like this:

class VirtualSuperClass
{
protected:
    SomeType m_someMember;
    // ...
public:
    virtual void doSomething() = 0;
};

class Subclass_1 : public VirtualSuperClass
{
protected:
    SomeType m_someSubclassMember;
    // ...
public:
    virtual void doSomething() { /* do something*/ }
};

class Subclass_2 : public VirtualSuperClass
{
protected:
    SomeType m_someOtherSubclassMember;
    // ...
public:
    virtual void doSomething() { /* do something else*/ }
}

在我的主要方法中,我填充了超类指针的向量,并为每个元素调用函数doSomething().

In my main method I fill a vector of pointers of the superclass and call the function doSomething() for every element.

int main()
{
    std::vector<VirtualSuperClass*> vec;
    vec.push_back(new Subclass_1());
    vec.push_back(new Subclass_2());
    vec.push_back(new Subclass_2());
    vec.push_back(new Subclass_1());
    // and so on, about 40,000 elements (not really done with .push_back :) ) ...

    // this actually runs in an application loop
    for (size_t i = 0; i < vec.size(); i++)
    {
        vec[i]->doSomething();
    }

    // ...

    for (size_t i = 0; i < vec.size(); i++)
    {
        delete vec[i];     // <-- pretty slow for large number of elements
        vec[i] = NULL;
    }
    vec.clear();
    return 0;
}

推荐答案

您可能正在寻找的一件事是为您分配的类创建自定义分配器-通过这种方式,您可以有效地获取内存并将其释放到系统中,而不是然后细小的片段-这可能是不修改此系统即可改善该系统整体"性能的唯一解决方案(这给您带来了瓶颈,肯定是个好主意;)).

One thing you may be looking for is a custom allocator for the classes you allocate - this way you can effectively get and release memory to the system in bulk rather then in tiny fragments - it's probably the only solution for improving "overall" performance of this system without modifying it (which given your bottleneck sure looks like a good idea ;) ).

这篇关于删除指针的STL向量条目的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆