Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page