Finding and deleting an element from a vector of pointers?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
    vector<unsigned int> x;
    vector<unsigned int>::iterator itr;
    unsigned int varF;
    ...
    ....
    
    // find and delete an element from a vector.
    itr = std::find(x.begin(), x.end(), varF);  // <algorithm>
    if (itr != x.end()) 
	x.erase(itr);
    //or
    x.erase(std::remove(x.begin(), x.end(), varF), x.end()); 


Now i decide to convert this vector with a vector of pointers

vector<unsigned int*> x;so how i can convert above functionality for a vector of pointers?
Thanks in advance.
Since you are using a vector of pointers, you must delete the referenced item or you will have a memory leak.

I personally recommend you use some form of smart pointer (but not the standard "smart" pointers, which are actually too stupid), that does a simple reference count (like the Boost shared_ptr<> http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm ) to store your items.

If not, you will have to do some memory management yourself. If you are sure you are ready to delete your pointer(s), you will have to do it correctly:

Helper to find values
1
2
3
4
5
6
7
8
9
10
template <typename T>
struct dereferences: public std::unary_function <const T*, bool>
{
    T value;
    dereferences( T value ): value( value ) { }
    bool operator () ( const T* v ) const
    {
        return *v == value;
    }
};

Delete a single item
1
2
3
4
5
6
itr = std::find_if(x.begin(), x.end(), dereferences <unsigned int> (varF));
if (itr != x.end())
{
    delete (*itr);
    x.erase(itr);
}

Delete multiple items
1
2
3
4
5
6
7
8
9
template <typename T>
struct delete_ptr: public std::unary_function <T*, bool>
{
    bool operator () ( T* ptr ) const
    {
        delete ptr;
        return true;
    }
};
1
2
3
itr = std::remove(x.begin(), x.end(), dereferences <unsigned int> (varF));
std::for_each(itr, x.end(), delete_ptr <unsigned int> ());
x.erase(itr, x.end());

There are, of course, a variety of ways to make this, er, shorter, but that ought to get you started...

Hope this helps.
Topic archived. No new replies allowed.