Sign in to follow this  
thecoast47

vector Clear method....C++

Recommended Posts

Lets say i have a vector of type CAT* and i add 3 cat pointers to the array:
[code]
int main(){
std::vector<CAT*> CAT_LIST;
CAT_LIST.push_back(new CAT());
CAT_LIST.push_back(new CAT());
CAT_LIST.push_back(new CAT());
}
[/code]
So my question is.... can i just call the .clear() method in order to delete and remove pointers from the vector ?
-or- do i have to loop through the vector and call the delete keyword on every pointer and then clear the null pointers from the list like this:
[code]
int main(){
for (int K = 0 ; K < (int)CAT_LIST.size();K++){
delete CAT_LIST[K];
}
CAT_LIST.clear();
}
[/code]

Share this post


Link to post
Share on other sites
You have to loop through and delete each object the pointers point to. Vectors simply destruct the objects they contain. In this case it contains pointers, which have no destructor, so destroying one doesn't do much.

Or use a type to hold your pointer that deletes the object in its destructor (a "smart pointer")

Also, negative sizes or indices don't make sense, so use unsigned types for sizes/indexes. Preferably std::size_t so things like porting 32bit->64bit are far less painful.

Share this post


Link to post
Share on other sites
Small tip: use iterators to loop over the vector instead of indices, and you don't need to worry about no signs.

[code]for (std::vector<CAT*>::iterator i = CAT_LIST.begin(), end = CAT_LIST.end(); i != end; ++i)
delete *i;
CAT_LIST.clear();[/code]

[font="CourierNew, monospace"] [/font]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this