简体   繁体   English

仅使用1行c ++初始化2d向量

[英]initializing 2d vector using only 1 line c++

I need to be able to initialize a 2D vector of int's in the same line in which I create it. 我需要能够在创建它的同一行初始化 int的2D向量。

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 . 更具体地说,我必须创建3x2大小的2D向量,并仅使用1行代码即可将其所有值设置为0。

Is there a way this can be done without using a for loop and several lines of code? 有没有一种方法可以不使用for循环和几行代码来完成?

尝试这个:

std::vector<std::vector<int>> twoDimVector(3, std::vector<int>(2, 0));

If you have small 2d vectors (like as you suggested) it can be achieved (using brace-init ) quity easily. 如果您有较小的2d向量(如您所建议的),则可以很容易地(使用brace-init )实现它。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM