std::vector<int> myVec[5]
creates a C-style array with 5 elements, each element is a std::vector.
In essence a 2D container is being instantiated. The container has 5 rows, fixed. Rows can't be added or deleted.
The number of columns is variable, the std::vector holds the columns for each row, and at container creation the number of columns is zero (0). The number of columns can be changed as desired later, and each row can have a differing number of columns.
Same idea with
std::list<int> myList[10]
, a 2D container with a fixed number of rows (10) and a variable number of columns using a std::list.
Mixing C and C++ containers for a multi-dimensional container is a bit odd, though it is doable. Better would be to use either C or C++ containers instead of mixing and matching.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <array>
#include <vector>
#include <list>
int main()
{
// 2D container, 5 rows, fixed;
// 1 column, can't change the number.
int myArr[5][1];
// 2D container, 5 rows, fixed;
// zero columns that can be changed.
std::array<std::vector<int>, 5> myVec;
// 2D container, 10 rows, fixed;
// zero columns that can be changed.
std::array<std::list<int>, 10> myList;
}
|
Choosing the 2nd dimension container, std::vector or std::list, could depend on how you want to modify and access the elements.
Using std::array instead of a C-style/regular array makes using C++ algorithms easier and more generic.
std::array doesn't devolve to a pointer when passed into a function, unlike a regular array.