bsoundra
bsoundra

Reputation: 970

Initialize a 2 Dimensional vector<int> in CPP

How to initialize a 2 dimensional vector<int> in C++?

For instance I have 4 arrays each of length 8 ints, like the 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 this

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

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

But this gives error. I even tried supplying the array a1 to v1 and passed v1 to aa[i] , still it fails.

So what would be the proper way of initializing the elements of a 2 dimensional vector<int>

Upvotes: 3

Views: 7471

Answers (3)

fredoverflow
fredoverflow

Reputation: 263360

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);
}

Upvotes: 2

aschepler
aschepler

Reputation: 72473

The initialization of aa also initialized all four of the contained vector<int> objects, using the default constructor for vector<int>. So you'll need to add data to those empty vectors, not initialize them.

Try for example:

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

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

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

Upvotes: 2

Related Questions