How to Delete Pointers in Vector or Map in Single Line?

2 03 2009


If you have two or three STL containers which holds pointers in your class as members, then I’m sure that its destructor will be the worst readable one. For deallocating STL containers, we have to iterate through each container by for loop, then delete it. But is there any single line function call to delete all pointers in vector or map, just like chopping the top of a tray of eggs at once? 😉

deletestlcontainers
Picture Courtesy – elitalice.com


You can use for_each() and functors to achieve this. Check out the code snippet.

1) How to delete Vector of pointers in single line

// Necessary headers.
#include "functional"
#include "vector"
#include "algorithm"

using namespace std;

// Functor for deleting pointers in vector.
template<class T>
struct DeleteVectorFntor
{
    // Overloaded () operator.
    // This will be called by for_each() function.
    bool operator()(T x) const
    {
        // Delete pointer.
        delete x;
        return true;
    }
};

// Test Function.
void TestVectorDeletion()
{
    // Add 10 string to vector.
    vector<CString*> StringVector;
    for( int Index = 0; Index < 10; ++Index )
    {
        StringVector.push_back( new CString("Hello"));
    }

    // Now delete the vector in a single  line.
    for_each( StringVector.begin(),
              StringVector.end(),
              DeleteVectorFntor<CString*>());
}

1) How to delete Map of pointers in single line

// Necessary headers.
#include "functional"
#include "map"
#include "algorithm"

using namespace std;

// Functor for deleting pointers in map.
template<class A, class B>
struct DeleteMapFntor
{
    // Overloaded () operator.
    // This will be called by for_each() function.
    bool operator()(pair<A,B> x) const
    {
        // Assuming the second item of map is to be
        // deleted. Change as you wish.
        delete x.second;
        return true;
    }
};

// Test function.
void TestMapDeletion()
{
    // Add 10 string to map.
    map<int,CString*> StringMap;
    for( int Idx = 0; Idx < 10; ++Idx )
    {
        StringMap[Idx] = new CString("Hello");
    }

    // Now delete the map in a single  line.
    for_each( StringMap.begin(),
              StringMap.end(),
              DeleteMapFntor<int,CString*>());
}


STL is really a powerful toolkit. Isn’t it?


Targeted Audience – Intermediate.

Advertisements