2012-05-03 44 views
1

我想使用下面的代碼,我想用它來「未知大小的輸入」。例如有一個數組int cac[1000][1000]。我可以使用vector<vector<int> > array;,那麼我怎樣才能用-1來初始化它?有什麼建議麼?如何實現無限多維數組?

#include <sstream> 
#include <iostream> 
#include <vector> 
#include <cstdlib> 
#include <memory.h> 

using namespace std; 

int cac[1000][1000]; 
string res[1000][1000]; 
vector<string> words; 
int M; 

int go(int a, int b){ 
if(cac[a][b]>= 0) return cac[a][b]; 
if(a == b) return 0; 

int csum = -1; 
for(int i=a; i<b; ++i){ 
    csum += words[i].size() + 1; 
} 
if(csum <= M || a == b-1){ 
    string sep = ""; 
    for(int i=a; i<b; ++i){ 
     res[a][b].append(sep); 
     res[a][b].append(words[i]); 
     sep = " "; 
    } 
    return cac[a][b] = (M-csum)*(M-csum); 
} 

int ret = 1000000000; 
int best_sp = -1; 
for(int sp=a+1; sp<b; ++sp){ 
int cur = go(a, sp) + go(sp,b); 
if(cur <= ret){ 
    ret = cur; 
    best_sp = sp; 
} 
} 
res[a][b] = res[a][best_sp] + "\n" + res[best_sp][b]; 
return cac[a][b] = ret; 
} 


int main(int argc, char ** argv){ 
memset(cac, -1, sizeof(cac)); 
M = atoi(argv[1]); 
string word; 
while(cin >> word) words.push_back(word); 
go(0, words.size()); 
cout << res[0][words.size()] << endl; 
} 
+0

你期望'-1'具有什麼語義? – ildjarn

+0

我很困惑,你能解釋一下你想要做的更深入一點嗎? – pg1989

+0

無限數組是一個鏈表。這就是你想要的。 – Tejs

回答

0

你可以做的是使用一個關聯數組,其中關鍵是一對(rowPositionColumnPosition)。當您想設置array[i][j]時,您只需添加或更新值assoArray[Pair(i,j)]。您可以假定任何不在關聯數組中的元素都具有初始值。

一般來說無限多維數組用於理論目的。我希望我沒有誤解這個問題。

0

從STL使用std :: vector比下面的解決方案更直截了當,該解決方案在本文的評論中被指出。我發現這個網站有效地解釋了這個話題:http://www.learncpp.com/cpp-programming/16-2-stl-containers-overview/

一個無限大小的數組實際上是不可能的。但是,您可以使用動態分配基本實現該效果。下面是一些示例代碼:

int counter = 0; 
int* myArray = new int[1000]; 

裝滿數據的陣列,每次添加一個值遞增計數器。當計數器達到1000,請執行下列操作:

int* largerArray = new int[2000]; 
for(int i = 0; i < 1000; i++) 
{ 
    largerArray[i] = myArray[i]; 
} 
delete[] myArray; 
myArray = largerArray; 

使用這種方法,您可以創建一個無限大小的數組最接近可能的,我不相信性能會與複製件的問題

+0

我不認爲這種錯誤是值得我的文章downvote。你說的沒錯,好建議 – TheResolute

+0

我的讚譽是激勵你改變你的帖子。一旦你這樣做,它將被撤回。 –

+0

我沒有意識到這是可能的。這很有趣,謝謝你的提示XD。 – TheResolute