Skip to content

[C++] 二維或更高維的 std::vector 初始化筆記

在撰寫 C++ 的過程中,我們若是想要儲存一筆陣列資料,除了使用最基礎的 array 資料結構外,就是使用標準函式庫中的 vector 了。然而並不是所有的資料都是單純的一維資料,有時我們可能有著需求要建立二維甚至更高維的初始化資料;本篇文章就是紀錄該如何做到這件事的筆記。

大致上有以下幾種方法:

  • 宣告時初始化(適用於 C++11 及更高版本)
  • push_back()
  • resize()
  • 填充建構

宣告時初始化

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



int main() {
    // Init
    vector<vector<int>> matrix {
        {1, 1, 1, 1},
        {2, 2, 2, 2},
        {3, 3, 3, 3}
    };

    // Print
    for (auto row: matrix) {
        for (auto val: row) {
            printf("%d ", val);
        }
        printf("\n");
    }
  
    return 0;
}


Output:

1 1 1 1 
2 2 2 2 
3 3 3 3 


跟原本宣告一維時基本相同,就是改成了宣告二維的形式。不過這要注意 C++ 的版本限制,最少要 C++ 11 開始才支援這個方法。


push_back()

簡單粗暴地一個個傳入 vector 中。

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


int main() {
    // Settints
    int m = 3;
    int n = 4;

    // Init
    vector<vector<int>> matrix;

    for (int i=0; i<m; ++i) {
        vector<int> row;

        for (int j=0; j<n; ++j) {
            row.push_back(i+1);
        }

        matrix.push_back(row);
    };

    // Print
    for (auto row: matrix) {
        for (auto val: row) {
            printf("%d ", val);
        }
        printf("\n");
    }
  
    return 0;
}


Output:

1 1 1 1 
2 2 2 2 
3 3 3 3 

resize()

resize() 是一個 vector 中用來重新設定特定尺寸的方法,我們也可以使用時一併設定初始值。

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


int main() {
    // Settints
    int m = 3;
    int n = 4;

    // Init
    vector<vector<int>> matrix(m);

    for (int i=0; i<m; ++i) {
        matrix[i].resize(n, i+1);
    };

    // Print
    for (auto row: matrix) {
        for (auto val: row) {
            printf("%d ", val);
        }
        printf("\n");
    }
  
    return 0;
}


Output:

1 1 1 1 
2 2 2 2 
3 3 3 3 


感覺上這個方法比 push_back() 又更簡潔。


填充建構

這應該是最推薦的簡單寫法了,只需要一行就能完成初始化。唯一的問題是只能初始化同樣的數值,不能像上方的範例那樣分行設定、甚至細緻到分項設定。

有利就有弊。

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


int main() {
    // Settints
    int m = 3;
    int n = 4;

    // Init
    vector<vector<int>> matrix(m, vector<int>(n, 1));

    // Print
    for (auto row: matrix) {
        for (auto val: row) {
            printf("%d ", val);
        }
        printf("\n");
    }
  
    return 0;
}


Output:

1 1 1 1
1 1 1 1
1 1 1 1

References


Read More

Tags:

Leave a Reply