温馨提示×

C++二维向量的初始化方法有哪些

c++
小樊
102
2024-08-19 22:31:31
栏目: 编程语言

  1. 利用嵌套vector进行初始化:
#include <vector>

std::vector<std::vector<int>> vec2d = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
  1. 使用resize()函数初始化指定大小的二维向量:
#include <vector>

int rows = 3;
int cols = 3;
std::vector<std::vector<int>> vec2d;
vec2d.resize(rows, std::vector<int>(cols, 0));
  1. 使用循环初始化二维向量:
#include <vector>

int rows = 3;
int cols = 3;
std::vector<std::vector<int>> vec2d(rows, std::vector<int>(cols));

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        vec2d[i][j] = i * cols + j + 1;
    }
}

0