[Solved] STL vector containing vector causing segfault


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;
}

1

solved STL vector containing vector causing segfault