Question

I would like to know how to de-allocate memory of an object inside a pair of a vector.

vector< pair<int, object*> > vectorObject;

I did try using an iterator to iterate through all the elements, but I am unsure of how to delete an object that is inside a pair.

for (vector< pair<int, object*> >::iterator it = vectorObject.begin(); it != vectorObject.end(); ++it) {
    // delete?
}

Hopefully someone will be kind enough to advise!

Was it helpful?

Solution

`The straight answer is:

for (vector< pair<int, object*> >::iterator it = vectorObject.begin(); it != vectorObject.end(); ++it) {
    delete it->second;
}

But. You should probably not be doing this.
Having unmanged pointers is a BAD idea. You should change the type of the vector to use std::unique_ptr.

vector< pair<int, std::unique_ptr<object>>>  vectorObject;

This is because manually deleting objects is error prone and unless you take safeguards (by uisng RAII) NOT exception safe.

OTHER TIPS

Just do:

for (vector< pair<int, object*> >::iterator it = vectorObject.begin(); it != vectorObject.end(); ++it) {
    delete it->second;
}

Or dereference the iterator and delete the second:

typedef pair<int, object*> mypair;

for (vector< mypair >::iterator it = vectorObject.begin(); it != vectorObject.end(); ++it) {
    mypair &current = *it;
    delete current.second;
}

You can also use the range-based for loop in C++11:

for (const auto& pair : vectorObject)
    delete pair.second;

And since we're already talking about C++11, you might as well change your container to:

std::vector<std::pair<int, std::unique_ptr<object>>> vectorObject;

Always prefer smart pointers to handle object ownership in C++11.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top