Removing the elements of a std vector object using erasure: a) memory handling and b) best way?
I have vec_A
one that stores instances class A
as:vec_A.push_back(A());
I want to remove some elements in the vector at a later stage and ask two questions: a) The element is removed like: vec_A.erase(iterator)
Is there any additional code I need to add to make sure there is no memory leak ?,
b) Suppose there is a condition if(num <5)
if num refers to a specific list number. With this in mind, is there a better way to remove 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;
}
a source to share
a) The item is removed as: vec_A.erase (iterator) Is there any additional code I need to add to make sure there is no memory leak ?.
Yes, that's all you have to do. There will be no memory leak. Since you did not allocate the yoour object on the heap when you did vec_A.push_back (A ()), the new object is copied to the vector. When you remove the vector will take care of removing the elements.
Suppose if condition (num <5) equals if num refers to numberList. With this in mind, is there a better way to remove the elements of a vector than what I am illustrating below?
Yes, you can remove / erase the idiom. That's 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;
}
a source to share
1) Resource processing is done by the class itself. The class destructor is responsible for no memory leak.
2) Removing elements from a vector is best done back:
for (std::vector<A>::reverse_iterator it = vec_A.rend(); it != vec_A.rbegin(); --it)
{
if (it->getNumber() < 5) {vec_A.erase(it.base());}
}
a source to share