initializing 2d vector using only 1 line c++

自古美人都是妖i 提交于 2020-12-13 04:58:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!