2011-04-27 73 views
1

我需要調整(未知大小的)的二維矢量,如下所示:如何動態調整二維矢量?

//Creating the vector of vectors: 

vector< vector<long> > v; 

//Resizing the vectors: 

/*Needing help here: 

my current assumption is: 
v.resize(1); 
v[0].resize(1); 
*/ 

//Adding elements: 

v[0][0].push_back(0); 
v[0][1].push_back(-1); 

在施加的push_back編譯器報告錯誤。我想我在調整矢量大小時遇到​​問題。

目標是創建一個二維向量,根據添加的值動態分配內存。

在此先感謝您的幫助

回答

2

您關於調整兩個維度的假設是正確的,但是您在push_back上發生錯誤,因爲v[0][0]的類型是long &而不是vector<long> &

我想你想:

v.resize(1); 
//Don't resize the second dimension because you want it to grow dynamically 
//v[0].resize(1); 
v[0].push_back(0); 
v[0].push_back(-1); 

請記住儘管這僅僅的push_back重新調整該特定行/列。如果您對v[0]v[1]等添加相同數量的元素不一致,則最終會出現「鋸齒狀」數組。你可能想把整個事情都包裝在一個類中來強化這種一致性。

+1

「你可能想把這整件事整理在課堂上來強化這種一致性。」請不要自己動手;使用'boost :: multi_array'。 – 2011-04-27 17:38:07

+0

非常感謝!我認爲你的解決方案對我而言是最準確的解決方案。 – CompilingCyborg 2011-04-27 18:11:46

2

您的假設是正確的。但是,如果你想調整所有內部向量,那麼這樣做:

vector< vector<long> > v;  
v.resize(10); 
for(size_t i = 0 ; i < 10 ; i++) 
    v[i].resize(20); 

請記住,當你使用vv[i][j],然後確保0<=i<100<=j< 20


現在爲什麼你在做什麼錯誤?

v.resize(1); 
v[0].resize(1); //that means, the constraint is : `0<=i<1` and `0<=j<1` 

v[0][0].push_back(0); 
v[0][1].push_back(-1); //problematic line! 

你得到錯誤,因爲你當你調用push_back秒時間不確保0<=i<10<=j<1約束。

1
// your current assumption is: 
v.resize(1); 
v[0].resize(1); 
// modify the value 
v[0][0] = new_value; 

// resize again 
v.resize(2); 
for (iterator iter = v.begin(); iter != v.end(); ++iter) 
    iter->resize(2); 

這是一種可能且正確的方法。

1

你的假設是正確的,替代嵌套容器是Boost multi_array,但它不太普遍。