问题
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?
回答1:
Try this:
std::vector<std::vector<int>> twoDimVector(3, std::vector<int>(2, 0));
回答2:
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
来源:https://stackoverflow.com/questions/40887674/initializing-2d-vector-using-only-1-line-c