4

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 ?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Jaeger
  • 159
  • 4
  • 14

3 Answers3

6

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.

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
3

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}
};
YoungJohn
  • 946
  • 12
  • 18
  • Things to look into for more information include initializer_lists and uniform initialization in c++11. – YoungJohn Feb 13 '14 at 15:21
  • @juanchopanza That works just as well in this case. My personal preference is for 'Almost Always Auto'. In this situation it makes little difference since we're committed to the type std::vector>, and we're not saving on any typing. Here it is simply a matter of style. Ideally, it serves to inform the programmer not to think of yy as a vector of vectors, but rather to think of it as any 2D container, though a better name for yy may be desired to drive that point home. – YoungJohn Feb 13 '14 at 15:39
  • 2
    That really makes no sense at all. Because the thing on the RHS is explicitly a vector of vectors. Also, this requires that the copy constructor be accessible. In this case it works, but it doesn't always. It is an extra restriction for little gain. – juanchopanza Feb 13 '14 at 15:43
  • It does not require that a copy constructor be accessible, it requires that either a copy constructor or a move constructor be accessible, and yes that is a restriction, but in this case that restriction is also imposed by using std::vector which requires that objects be copyable or movable, so there is no real difference other than style in this case. – YoungJohn Feb 13 '14 at 16:09
3

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).

Shiv
  • 207
  • 2
  • 5