List of initializers on two-dimensional std :: array

Why is a two-dimensional int array initialized contiguously? Meanwhile, a two-dimensional vector is initialized to many numbers.

int main()
{
  array<array<int, 2>, 2> td{ 2, 6, 4, 8 }; //array of arrays
  for (int i = 0; i < 2; ++i)
    for(int j = 0; j < 2; ++j)
      cout << td[i][j] << ' ';

  cout << endl;

  vector<vector<int>> vtd{ { 5, 1 }, { 0, 2 } };  //vector of vectors
  for (int i = 0; i < 2; ++i)
    for (int j = 0; j < 2; ++j)
      cout << vtd[i][j] << ' ';

  return 0;
}

Here are the results:

2 6 4 8
5 1 0 2
+3
source share
4 answers

std::arrayis an aggregate. When an aggregate is initialized using a list with an extended list like this, each subordinate, in order, takes as many items from the list as needed, and the rest of the list is used to initialize the next item, and so on. In particular, this means that the first array in tdaccepts the first two initializers (since it has two elements), and the second array accepts the remaining two.

std::vector , std::initializer_list , .

+3

.

std::array ( ), std::vector .

+1

std::vector - , : { T* data, size_t count, size_t capacity }. - .

, std::array - C-. , C-.

std::vector<int> v;
v.reserve(4);
std::array<int, 4> a;

:

[ int* v.data ]
[ size_t v.count = 0 ]
[ size_t v.size = 4 ]
[ int[4] ]

2- std::vector ,

[ std::vector<int>* v.data --> points to second tier object in heap memory ]
[ size_t v.count ]
[ size_t v.size ]

std::array int a[2][2], , .

+1

std::array - . , , , , .

:

std::array<T, 4> a;
|   a[0]   |   a[1]   |   a[2]   |   a[3]   |

std::array<std::array<T, 2>, 2> b;
|   a[0][0]   |   a[0][1]   |   a[1][0]   |   a[1][1]   |

(a[0]) ( ), , .

For a vector, it is determined at run time. A dynamic vector array is guaranteed to be contiguous if it is a vector of vectors, each element in the parent vector has a pointer to a separate block of adjacent memory (each "child" vector has size, capacity, and a pointer to a block of adjacent memory).

Similarly follows:

T t[...][...] ====> std::array<std::array<T, ...>, ...>
T** t         ====> std::vector<std::vector<T>>
0
source

All Articles