vector定义与初始化的巧妙用法

本文介绍了C++中使用vector进行二维数组初始化的两种不同方式及其效果对比。一种是直接利用数组长度进行初始化,另一种是使用预定义的变量。文章通过实例展示了这两种初始化方式的区别,并解释了为什么使用具体数字而非变量进行初始化的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector定义与初始化的巧妙用法

例子1:

代码中的8和3换成定义好的m和n变量,则无法通过编译。
代码:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> mat[8](vector<int>(3));

    for(int i = 0;i < 8;i++)
        for(int j = 0;j < 3;j++)
            mat[i][j] = i+j*3;

    return 0;
}

结果:

(gdb) print mat
$1 = {std::vector of length 3, capacity 3 = {0, 3, 6}, std::vector of length 3, capacity 3 = {
    1, 4, 7}, std::vector of length 3, capacity 3 = {2, 5, 8}, 
  std::vector of length 3, capacity 3 = {3, 6, 9}, std::vector of length 3, capacity 3 = {4, 
    7, 10}, std::vector of length 3, capacity 3 = {5, 8, 11}, 
  std::vector of length 3, capacity 3 = {6, 9, 12}, std::vector of length 3, capacity 3 = {7, 
    10, 13}}

例子2:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int m = 3, n = 4;

    vector<vector<int>> mat(m, vector<int>(n, 0));
    for(int i = 0;i < m;i++)
        for(int j = 0;j < n;j++)
            mat[i][j] = i*2+j*3;

    return 0;
}

运行结果:

(gdb) print mat
$1 = std::vector of length 3, capacity 3 = {std::vector of length 4, capacity 4 = {0, 3, 6, 
    9}, std::vector of length 4, capacity 4 = {2, 5, 8, 11}, 
  std::vector of length 4, capacity 4 = {4, 7, 10, 13}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值