deleting element objects of a std vector using erase : a) memory handling and b) better way?

Posted by memC on Stack Overflow See other posts from Stack Overflow or by memC
Published on 2010-04-30T09:16:38Z Indexed on 2010/04/30 9:17 UTC
Read the original article Hit count: 271

Filed under:
|
|

hi,

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;
}

© Stack Overflow or respective owner

Related posts about stdvector

Related posts about c++