Q:

STL vector containing vector causing segfault

The following code causes a segfault when I try to issue my push_back call.  What am I doing wrong?
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    std::string * foo = new std::string("hello world");
    cout << *foo << endl;

    std::vector<std::vector<std::string *> > my_vecs;
    my_vecs[0].push_back(foo); // segfaults
    cout << "trying to print my_vecs size of " << my_vecs.size() << " but we never reach that point due to segfault " << endl;
    return 0;
}

I'm pretty sure I'm violating one of the contracts for using vector, as the problem is surely not with the STL implementation.

A:

The outer vector must first be explicitly grown, before one can push to its elements.  
This may be a little surprising since STL map's automatically insert their keys.  But, it's certainly the way it is.
#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    const int DESIRED_VECTOR_SIZE = 1;
    std::string * foo = new std::string("hello world");
    cout << *foo << endl;

    std::vector<std::vector<std::string *> > my_vecs;

    for (int i = 0; i < DESIRED_VECTOR_SIZE; ++i) {
        std::vector<std::string *> tmp;
        my_vecs.push_back(tmp); // will invoke copy constructor, which seems unfortunate but meh
    }

    my_vecs[0].push_back(foo); // segfaults
    cout << "now able to print my_vecs size of " << my_vecs.size() << endl;
    return 0;
}

