欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c++之vector

程序员文章站 2022-03-23 17:04:01
...

二维vector初始化

  • 方法一
   int nums = 5;
   int a[5][5] = {{0, 10, -1, 4, 12},
                  {10, 0, 15, 8, 5},
                  {-1, 15, 0, 7, 30},
                  {4, 8, 7, 0, 6},
                  {12, 5, 30, 6, 0}};
   vector<vector<int> > graph(nums); //创建一个vector元素个数为nums
   for(int i = 0; i < nums; ++i){
      graph[i].resize(nums); //分配内存 值全为0
   }
   for(int i = 0; i < nums; ++i){
      for(int j = 0; j < nums; ++j){
         graph[i][j] = a[i][j];
      }
   }
  • 方法二
   int nums = 5;
   int a[5][5] = {{0, 10, -1, 4, 12},
                  {10, 0, 15, 8, 5},
                  {-1, 15, 0, 7, 30},
                  {4, 8, 7, 0, 6},
                  {12, 5, 30, 6, 0}};
   vector<vector<int> > obj(nums, vector<int>(nums));
   for(int i = 0; i < nums; ++i){
      for(int j = 0; j < nums; ++j){
         graph[i][j] = a[i][j];
      }
   }

vector.resize()的应用

例如生成杨辉三角:

vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result(numRows);
        for(int i = 0; i < numRows; ++i){
            result[i].resize(i+1); //resize()操作:创建指定数量的的元素并指定vector的存储空间
            result[i][0] = result[i][i] = 1;
            for(int j = 1; j < i; ++j){
                result[i][j] = result[i-1][j-1] + result[i-1][j];
            }
        }
        return result;
    }