6.4. Storing Pointers in a vector
Problem
For efficiency or other
reasons, you can’t store copies of your objects in a vector, but you need to keep track of them somehow.
Solution
Store pointers to your objects in a vector instead
of copies of the objects themselves. But if you do, don’t forget to delete the objects that are pointed to, because the vector won’t do it for you. Example 6-4 shows how to declare and work with
vectors of pointers.
Example 6-4. Using vectors of pointers
#include <iostream>
#include <vector>
using namespace std;
static const int NUM_OBJECTS = 10;
class MyClass { /*...*/ };
int main() {
vector<MyClass*> vec;
MyClass* p = NULL;
// Load up the vector with MyClass objects
for (int i = 0; i < NUM_OBJECTS; i++) {
p = new MyClass();
vec.push_back(p);
}
// Do something useful with this data, then delete the objects when
// you're done
for (vector<MyClass*>::iterator pObj = vec.begin();
pObj != vec.end(); ++pObj) {
delete *pObj; // Note that this is deleting what pObj points to,
// which is a pointer
}
vec.clear(); // Purge the contents so no one tries to delete them
// again
}Discussion
You can store pointers in a vector just like you
would anything else. Declare a vector of pointers like
this:
vector<MyClass*> vec;
The important thing to remember is that a vector
stores values without regard for what those values represent. It,
therefore, doesn’t know that it’s supposed to delete pointer values when it’s destroyed. If you allocate memory, then put pointers to that ...