I am trying to use an array of vector like this:
vector<foo*> *vec = new vector<foo*>(n);
Some positions of vec will be empty and some of them will be later on filled with some data:
vec[i].push_back(&foo_var);
My problem is the empty positions of vec. Let's say that for i equal to 0, I did not push_back anything. Then, when I try to do some check, for example,
vec[0].size();
instead of the expected return 0, the program returns a huge number 1457283635.
Searching around, I found that I should had initialized the empty positions. Then I try this:
vector<foo*> vec = new vector<for*>(n);
for(int i = 0; i < n; i++) {
vec[i] = vector<foo*>();
}
...
This "solution" was enough to make my program works as I expected (returning 0 as the size of an empty position, for instance).
However, after increasing the size of n, my program crashes in this line now:
vec[i] = vector<foo*>();
The program sends a segmentation fault error.
- Can someone please explain what is happening?
- How should I handle this specific case?
- What are the best practices for vector initialization in this case?
new vector<for*>(n);you have a typo here (in both places where this line appears)nullptr? Also I would seriously recommend using something likestd::vector<std::vector<std::unique_ptr<foo>>>.foris a keyword, it can't possibly appear as a typename invector<for>ninstead ofnvectors.new vector99% of the time means you are doing something wrong.