c++ vector二维数组

阅读数:55 评论数:0

跳转到新版页面

分类

C/C++

正文

#include <iostream>
#include <vector>

int main() {
    // 定义二维float数组
    std::vector<std::vector<float>> matrix;

    // 设置行数和列数
    size_t rows = 3;
    size_t cols = 4;

    // 初始化二维数组
    // 使用 resize 方法调整 matrix 的大小,并使用 std::vector<float>(cols, 0.0f) 初始化每一行,默认值为 0.0f。
    matrix.resize(rows, std::vector<float>(cols, 0.0f));

    // 通过索引访问和设置值
    for (size_t i = 0; i < rows; ++i) {
        for (size_t j = 0; j < cols; ++j) {
            matrix[i][j] = static_cast<float>(i * cols + j);
        }
    }

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

    return 0;
}



相关推荐