1

first of all I'm sorry if it is a duplicate I have not found what I need.

The question is how can I initialize vectors in 2D with empty values.

For my purpose I write:

vector<vector<int>> Example={{},{},{}};

So I can write for example:

for(int i=0;i< Example.size();i++)
    Example[i].push_back(i);

Now how can I write this thing:

vector<vector<int>> Example={{},{},{}}; 

in a smart (and more correct) way?

MementoMori
  • 283
  • 4
  • 10
  • 1
    Does this answer your question? [Initializing a 2D vector using initialization list in C++11](https://stackoverflow.com/questions/17714552/initializing-a-2d-vector-using-initialization-list-in-c11) – alteredinstance Jan 20 '20 at 17:00
  • 1
    `vector> Example(3);`. – HolyBlackCat Jan 20 '20 at 17:00
  • 1
    Something to know, vectors will always store initialized objects or values only. To experiment with this, write a class that prints something in its argument-less (default-)constructor and then create a vector of this class. If you use resize(10) on that vector, you will see that the constructor was called 10 times. Same if you create the vector directly with 10 elements like the answers here suggest. The default "constructor" for integers is just 0. This is the difference to native arrays by the way which can give you garbage memory instead of default-initialized values. – AlexGeorg Jan 20 '20 at 17:47

1 Answers1

1

Here is a demonstrative program.

#include <iostream>
#include <vector>

int main() 
{
    std::vector<std::vector<int>> v( 3 );

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335