Initialize 2-dimensional vector <int> in CPP

How to initialize two-dimensional vector<int>in C ++?

For example, I have 4 arrays of length 8 int, as shown below

int a1[] = {1,2,3,4,5,6,7,8};
int a2[] = {1,2,3,4,9,10,11,12};
int a3[] = {1,2,5,6,9,10,13,14};
int a4[] = {1,3,5,7,9,11,13,15};

and i have it

vector< vector <int> > aa (4);

aa[i] (a1,a1+8);

But this gives an error. I even tried to provide an array from a1 to v1 and passed v1 to aa[i], but still it fails.

So what would be the correct way to initialize two-dimensional elements vector<int>

+3
source share
3 answers
aa[i].assign(a1,a1+8);
+2
source
int arr[4][8] =
{
    {1, 2, 3, 4, 5,  6,  7,  8},
    {1, 2, 3, 4, 9, 10, 11, 12},
    {1, 2, 5, 6, 9, 10, 13, 14},
    {1, 3, 5, 7, 9, 11, 13, 15},
};

std::vector<std::vector<int> > vec(4, std::vector<int>(8));
for (int i = 0; i < 4; ++i)
{
    vec[i].assign(arr[i], arr[i] + 8);
}
+2
source

aa vector<int>, vector<int>. , .

, :

std::copy(a1, a1+8, std::back_inserter(aa[i]));
0
source

Source: https://habr.com/ru/post/1772940/


All Articles