Reputation: 27
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!
Upvotes: 0
Views: 1493
Reputation: 3325
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.
Upvotes: 0
Reputation: 264571
`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.
Upvotes: 2
Reputation: 13298
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 ¤t = *it;
delete current.second;
}
Upvotes: 0