使用擦除删除 std 向量的元素对象:a)内存处理和 b)更好的方法?

发布于 2024-08-31 08:07:07 字数 1513 浏览 1 评论 0原文

我有一个 vec_Aclass A 的实例存储为: vec_A.push_back(A());

我想删除向量在稍后阶段,有两个问题:a)元素被删除为:vec_A.erase(iterator) 我需要添加任何其他代码以确保没有内存泄漏吗? 。

b) 假设条件if(num <5)是num是否在特定的numberList中。鉴于此,是否有比我下面说明的更好的方法来删除向量的元素?

#include<vector>
#include<stdio.h>
#include<iostream>

class A {
      public:

             int getNumber();            
             A(int val);
             ~A(){};
      private:
              int num;
};

A::A(int val){
         num = val;
         };

int A::getNumber(){
    return num;
};

int main(){


    int i  =0;
    int num;
    std::vector<A> vec_A;
    std::vector<A>::iterator iter;

          for ( i = 0; i < 10; i++){
              vec_A.push_back(A(i));
          }
          iter = vec_A.begin();

          while(iter != vec_A.end()){
              std::cout <<  "\n --------------------------";
              std::cout <<  "\n Size before erase =" << vec_A.size();
              num = iter->getNumber() ;
              std::cout <<  "\n num = "<<num;
              if (num < 5){
                      vec_A.erase(iter);
                      }
              else{
                   iter++;
                   }

              std::cout <<  "\n size after erase =" << vec_A.size();
          }        


    std::cout << "\nPress RETURN to continue...";
    std::cin.get();

    return 0;
}

I have a vec_A that stores instances of class A as: vec_A.push_back(A());

I want to remove some elements in the vector at a later stage and have two questions: a) The element is deleted as: vec_A.erase(iterator) Is there any additional code I need to add to make sure that there is no memory leak? .

b) Assume that condition if(num <5) is if num is among a specific numberList. Given this, is there a better way to delete the elements of a vector than what I am illustrating below?

#include<vector>
#include<stdio.h>
#include<iostream>

class A {
      public:

             int getNumber();            
             A(int val);
             ~A(){};
      private:
              int num;
};

A::A(int val){
         num = val;
         };

int A::getNumber(){
    return num;
};

int main(){


    int i  =0;
    int num;
    std::vector<A> vec_A;
    std::vector<A>::iterator iter;

          for ( i = 0; i < 10; i++){
              vec_A.push_back(A(i));
          }
          iter = vec_A.begin();

          while(iter != vec_A.end()){
              std::cout <<  "\n --------------------------";
              std::cout <<  "\n Size before erase =" << vec_A.size();
              num = iter->getNumber() ;
              std::cout <<  "\n num = "<<num;
              if (num < 5){
                      vec_A.erase(iter);
                      }
              else{
                   iter++;
                   }

              std::cout <<  "\n size after erase =" << vec_A.size();
          }        


    std::cout << "\nPress RETURN to continue...";
    std::cin.get();

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌能量女王 2024-09-07 08:07:07

a) 元素被删除为:
vec_A.erase(iterator) 有没有
我需要添加额外的代码来制作
确定没有内存泄漏? .

是的,这就是您需要做的全部。不会出现内存泄漏。由于您没有在堆上分配对象,因此当您执行 vec_A.push_back(A()) 时,一个新对象将复制到向量中。当你擦除时,向量将负责删除元素。

假设条件 if(num <5) 是 if
num 是一个特定的数字列表。
鉴于此,有没有更好的方法
删除向量的元素
下面我要说明什么?

是的,您可以删除/擦除习惯用法。这是一个例子:

 class A
{
public:
    A(int n) : m_n(n)
    {
    }

    int get() const
    {
        return m_n;
    }
private:
    int m_n;
};

bool lessThan9(const A& a)
{
    return a.get() < 9;
}

//Or if you want for a generic number
struct Remover : public std::binary_function<A,int,bool>
{
public:
    bool operator()(const A& a, int n)const
    {
        return a.get() < n;
    }
};

int main()
{
    std::vector<A> a;
    a.push_back(A(10));
    a.push_back(A(8));
    a.push_back(A(11));
    a.push_back(A(3));

    a.erase(std::remove_if(a.begin(), a.end(), lessThan9), a.end());

    //Using the user-defined functor
    a.erase(std::remove_if(a.begin(), a.end(), std::bind2nd(Remover(), 9)), a.end());

    return 0;
}

a) The element is deleted as:
vec_A.erase(iterator) Is there any
additional code I need to add to make
sure that there is no memory leak? .

Yes, that's all you need to do. There will be no memory leak. Since you didn't allocate yoour object on heap, when you did vec_A.push_back(A()) a new object is copied into the vector. When you do erase, vector will take care of deleting the elements.

Assume that condition if(num <5) is if
num is among a specific numberList.
Given this, is there a better way to
delete the elements of a vector than
what I am illustrating below?

Yes, you can remove/erase idiom. This is an example:

 class A
{
public:
    A(int n) : m_n(n)
    {
    }

    int get() const
    {
        return m_n;
    }
private:
    int m_n;
};

bool lessThan9(const A& a)
{
    return a.get() < 9;
}

//Or if you want for a generic number
struct Remover : public std::binary_function<A,int,bool>
{
public:
    bool operator()(const A& a, int n)const
    {
        return a.get() < n;
    }
};

int main()
{
    std::vector<A> a;
    a.push_back(A(10));
    a.push_back(A(8));
    a.push_back(A(11));
    a.push_back(A(3));

    a.erase(std::remove_if(a.begin(), a.end(), lessThan9), a.end());

    //Using the user-defined functor
    a.erase(std::remove_if(a.begin(), a.end(), std::bind2nd(Remover(), 9)), a.end());

    return 0;
}
锦欢 2024-09-07 08:07:07

1)资源处理由类本身完成。类的析构函数负责确保不存在内存泄漏。

2) 从向量中删除元素最好从后到前进行:

for (std::vector<A>::reverse_iterator it = vec_A.rend(); it != vec_A.rbegin(); --it)
{
  if (it->getNumber() < 5) {vec_A.erase(it.base());}
}

1) Resource handling is done by the class itself. The destructor of a class is responsible to ensure that there is no memory leak.

2) Removing elements from a vector is best done back-to-front:

for (std::vector<A>::reverse_iterator it = vec_A.rend(); it != vec_A.rbegin(); --it)
{
  if (it->getNumber() < 5) {vec_A.erase(it.base());}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文