Insert elements in a multidimensional vector

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 4x4 array, instead 31x1 output with many empty elements, how to insert elements into a multidimensional vector?

+6
c ++ vector
Dec 18 '12 at 15:55
source share
2 answers

Do not think of it as a multidimensional vector, think of it as a vector of vectors.

 int n = 4; std::vector<std::vector<int>> vec(n, std::vector<int>(n)); // looping through outer vector vec for (int i = 0; i < n; i++) { // looping through inner vector vec[i] for (int j = 0; j < n; j++) { (vec[i])[j] = i*n + j; } } 

I have included parentheses in (vec[i])[j] for understanding only.

Edit:

If you want to fill your vector with push_back , you can create a temporary vector in the inner loop, fill it, and then click on its vector:

 for (int i = 0; i < n; i++) { std::vector<int> temp_vec; for (int j = 0; j < n; j++) { temp_vec.push_back(j); } vec.push_back(temp_vec); } 

However, push_back calls result in slower code, since you do not need to constantly redistribute the vector, but you must also create a temporary one and copy it.

+6
Dec 18 '12 at 15:59
source share

a vector<vector<int>> not the best implementation for multidimensional storage. The following implantation works for me.

 template<typename T> class array_2d { std::size_t data; std::size_t col_max; std::size_t row_max; std::vector<T> a; public: array_2d(std::size_t col, std::size_t row) : data(col*row), col_max(col), row_max(row), a(data) {} T& operator()(std::size_t col, std::size_t row) { assert(col_max > col && row_max > row) return a[col_max*col + row]; } }; 

precedent:

 array_2d<int> a(2,2); a(0,0) = 1; cout << a(0,0) << endl; 

This solution is similar to that described here .

+3
Dec 18 '12 at 16:28
source share



All Articles