Jaeger
Jaeger

Reputation: 159

How to initialize 2d vector using constructor in c++?

I know how to initialize 1d vector like this

int myints[] = {16,2,77,29};
std::vector<int> fifth(myints, myints + sizeof(myints) / sizeof(int));

suppose I have 2d data.

float yy[][2] = {{20.0, 20.0}, {80.0, 80.0}, {20.0, 80.0}, {80.0, 20.0}};

How can I initialize a 2d vector ?

Upvotes: 4

Views: 9729

Answers (3)

Shiv
Shiv

Reputation: 217

In case you do not know the values beforehand still you can initialize a 2D vector with an initial value.

vector< vector <int> > arr(10, vector <int> (10, 0));

The above code will initialize a 2D vector of 10X10 with all index value as zero(0).

Upvotes: 4

herohuyongtao
herohuyongtao

Reputation: 50657

In current C++ (since 2011) you can initialize such vector in constructor:

vector<vector<float>> yy
{
    {20.0, 20.0},
    {80.0, 80.0},
    {20.0, 80.0},
    {80.0, 20.0}
};

See it alive: http://ideone.com/GJQ5IU.

Upvotes: 6

YoungJohn
YoungJohn

Reputation: 956

In C++ 11 you can initialize a vector of vectors like this:

auto yy = std::vector<std::vector<float>>
{
    {20.0, 20.0},
    {80.0, 80.0},
    {20.0, 80.0},
    {80.0, 20.0}
};

Upvotes: 3

Related Questions