Jack Wilsdon
Jack Wilsdon

Reputation: 7045

Multidimensional vector bus error

I have a 11663 Bus Error when I attempt to do the following;

std::vector< std::vector<int> > bullets;
std::vector<int> num;
num[0] = 7;
bullets.push_back(num);

I thought this would work as the vector bullets's type is a vector. Why doesn't this work as expected? Also, the following works;

std::vector< std::vector<int> > bullets;
std::vector<int> num (4, 100);
bullets.push_back(num);

And I don't know why this works, but not my other code.

Upvotes: 1

Views: 650

Answers (2)

Code-Apprentice
Code-Apprentice

Reputation: 83587

num[0] = 7;

should be

num.push_back(7);

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124790

std::vector<int> num;
num[0] = 7;

num has not yet allocated storage for anything. Only use the indexing syntax [] if you know an element exists at that index. Otherwise, use push_back, which grows the vectors storage capacity if needed. The second example works because you used the constructor which reserves a certain amount of space for elements (4 in this case, all with the value 100).

std::vector<int> num;
num.push_back(7);
bullets.push_back(num);

On a side note, "this doesn't work" is not a very helpful problem description. Also, note that a vector of vectors used as a matrix is not a good idea in performance critical code should you need to iterate over each element.

Don't scrap it just yet and don't worry abut it unless you know for a fact that it will be a problem, but realize that you lose locality of data with this approach because each vector will allocate its storage separately. If this data is being iterated over in a tight loop you are better off allocating one big vector and calculating the offset to each individual position manually.

Upvotes: 4

Related Questions