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




Accessing empty vector will always throw exception?

23 07 2008


Vectors are cool! if we access out of array, they will throw unhandled exception. I used to get a lot. 🙂

But are you sure that you’re vector always throw exception if you access out of array?


Answer is NO. Well have a look at the code snippet. At first we access an empty vector which throws an exception. Then we insert some values and then clear the vector to make it empty. Then if we access the empty vector, it won’t throw exception! Have a look at it.

// This class is just to access the protected members
// of vector.
class IntVector : vector<int>
{
    friend void CheckVector();
};

void CheckVector()
{
    IntVector IntArray;

    try
    {
        // Try to access element which result in exception.
        int Value = IntArray[ 0 ];
    }
    catch( ... )
    {
        // It will reach here since we're trying
        // to access an empty vector.
    }

    // Now add one value and clear the vector.
    IntArray.push_back( 10 );
    IntArray.clear();

    try
    {
        // Now try to access element. You can access it
        // eventhough the vector is empty.
        int Value = IntArray[ 0 ];
    }
    catch( ... )
    {
        // It will not reach here.
    }

    // Check the size of memory allocation inside vector.
    int InternalSize = _msize( IntArray._First );
    int VectorSize = IntArray.size();

Well, the reason is optimization. While clearing the vector, for optimization it won’t removes the allocated memory. It just sets the size as 0. So if you access the data by using array operator, you’ll get old value.


The morel is always check the size of array before accessing it. Well the behavior is observed in Visual Studio 6.0. Different IDEs and platforms may show different behavior. Take care!


Targeted Audience – Intermediate.