1. 程式人生 > >vector的輸入

vector的輸入

今天筆試的時候浪費了很長時間在一個很小的知識點上,導致筆試有一道題沒有AC,非常氣憤!引以為戒~

二維向量的輸入問題:
不像二維陣列那樣,可以直接對arr[i][j]進行迴圈賦值。在vector<vector<int>>中,因為vector是一個容器,最外層的vector容器中放著更小的vector,而裡層的vector裡面放的是int型的數字。所以我們首先要對裡層的vector容器賦值,然後再把裡層的vector作為元素插入到外層的vector中。程式碼如下:

#include <iostream>
#include <vector>
using namespace std; int main() { vector<vector<int>> test; vector<int> v; int n,temp; cin >> n; test.clear(); //輸入 for (int i = 0; i<n; i++) { v.clear(); //每次記得clear:) for (int j = 0; j < n; j++) { cin >> temp; v.push_back(temp); } test.push_back(v); } //輸出
for(int i = 0; i < n; i++) { for(int j = 0;j < n; j++) { cout << test[i][j] << " "; } cout << endl; } return 0; }