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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/houzijushi/article/details/81905945

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}}

猜你喜欢

转载自blog.csdn.net/houzijushi/article/details/81905945