c++ vector初始化

转载https://blog.csdn.net/u014547577/article/details/77962281

  1. 一维vector

    • 大小:std::vector<int> v(9)

    • 大小和初值:std::vector<int> v(9, 0),大小为9,初值均为0。

    • 大小和不同的初值:

      int x[] = {1, 2, 3};
      std::vector<int> v(x, x + sizeof(x) / sizeof(x[0]));
      // or
      std::vector<int> v1(std::begin(x), std::end(x));
      // or c++ 11, vs12 not work
      std::vector<int> v({1, 2, 3})
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
  2. 二维vector

    • 大小: std::vector<std::vector<int>> v(5, std::vector<int>(6))相当于int v[5][6]

    • 大小和初值:std::vector<std::vector<int>> v(5, std::vector<int>(6, 0))相当于 int v[5][6]={0}

    • 大小和不同的初值:

      using namespace std;
      int x[2][3] = {{1, 2, 3}, {4, 5, 6}};
      vector<vector<int>> v(2, vector<int>(3));
      for(int i = 0; i < 2; i++){
       for(int j = 0; j < 3; j++){
           v[i][j] = x[i][j];
       }
      }
      // or C++ 11, vs12 not work
      vector<vector<int>> v1{{1, 2, 3},
                          {4, 5, 6}};

猜你喜欢

转载自blog.csdn.net/piaoliangjinjin/article/details/80762968