2011-06-12 43 views
2

我可以建立一個重複序列構造

vector<vector<int> > 

使用重複序列構造?

我知道我可以建立一個像

vector<int> v(10, 0); 

,但我不知道如何建立使用這種相同的方法載體的載體。謝謝!

回答

4

只要它傳遞一個矢量作爲第二個參數:

// 10 x 10 elements, all initialized to 0 
vector<vector<int> > v(10, vector<int>(10, 0)); 
4

vector<vector<int> > v(10, vector<int>(30, 0));將創建與每個30零10層的載體。

0
explicit vector (size_type n, const T& value= T(), const Allocator& = Allocator()); 

重複序列構造:初始化向量與其內容集合到一個重複,n次,value副本。

vector< vector<int> > vI2Matrix(3, vector<int>(2,0)); 

創建3個向量,每個向量2個零。

本質上,可以使用向量矢量來表示二維數組。

下面是一個源代碼示例:

#include <iostream> 
#include <vector> 

using namespace std; 

main() 
{ 
    // Declare size of two dimensional array and initialize. 
    vector< vector<int> > vI2Matrix(3, vector<int>(2,0));  

    vI2Matrix[0][0] = 0; 
    vI2Matrix[0][1] = 1; 
    vI2Matrix[1][0] = 10; 
    vI2Matrix[1][1] = 11; 
    vI2Matrix[2][0] = 20; 
    vI2Matrix[2][1] = 21; 

    cout << "Loop by index:" << endl; 

    int ii, jj; 
    for(ii=0; ii < 3; ii++) 
    { 
     for(jj=0; jj < 2; jj++) 
     { 
     cout << vI2Matrix[ii][jj] << endl; 
     } 
    } 
    return 0; 
}