vector<vector<int>> sort_a;
vector<int> v2;
vector<int> v3;
for (int i=0; i<4; ++i) {
v2.push_back(i);
for (int j=0; j<4; ++j) {
v3.push_back(j);
sort_a.push_back(v2);
sort_a.push_back(v3);
}
}
Vector sort_a should be a 4×4 array, instead the output is 31×1 with lots of empty elements, how do i insert elements in a multidimensional vector ?
Don’t think of it as a multidimentional vector, think of it as a vector of vectors.
I included parentheses in
(vec[i])[j]just for understanding.Edit:
If you want to fill your vector via
push_back, you can create a temporary vector in the inner loop, fill it, and then push_back it to your vector:However,
push_backcalls result in slower code, since not only you need to reallocate your vector all the time, but also you have to create a temporary and copy it.