2

I need to be able to initialize a 2D vector of int's in the same line in which I create it.

To be more specific, I have to create a 3x2 size 2D vector and set all of it's values to 0 using only 1 line of code.

Is there a way this can be done without using a for loop and several lines of code?

S.Mitchell
  • 91
  • 1
  • 2
  • 10

2 Answers2

7

Try this:

std::vector<std::vector<int>> twoDimVector(3, std::vector<int>(2, 0));
Adam Hunyadi
  • 1,890
  • 16
  • 32
1

If you have small 2d vectors (like as you suggested) it can be achieved (using brace-init) quity easily.

#include <vector>
#include <iostream>

int main(){

    std::vector<std::vector<int>> vec{ { 0, 0 }, { 0, 0 }, { 0, 0 } };

    std::cout << "vec size = " << vec.size() << "x" << vec[0].size() << std::endl;

    return 0;
}

Output:

vec size = 3x2
Stack Danny
  • 7,754
  • 2
  • 26
  • 55