温馨提示×

c++中怎么用vector定义二维数组

c++
小亿
97
2023-12-16 15:57:35
栏目: 编程语言

在C++中,可以使用vector<vector<T>>来定义二维数组,其中T是数组元素的类型。下面是一个示例代码:

#include <iostream>
#include <vector>

int main() {
    int rows = 3;
    int cols = 4;

    // 定义一个二维数组
    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));

    // 给二维数组赋值
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = i * cols + j + 1;
        }
    }

    // 打印二维数组
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

这段代码定义了一个3行4列的二维数组,然后使用两层循环给数组赋值,并打印出数组的内容。输出结果如下:

1 2 3 4 
5 6 7 8 
9 10 11 12

0