2013-03-16 28 views
0

我需要調整數組的大小並將值複製到那裏...所以我知道,我需要一個動態數組,但我不能使用vector並且必須使用靜態數組..我寫的是這樣的:C++動態數組 - 通過複製兩個數組

string names1[0]; 

bool foo(const char * inFile1) { 
int size = 0; 
ifstream myfile(inFile1); 
if (myfile.is_open()) { 
    // iterate through lines 
    while (getline(myfile, line)) {    
     string tmp[++size]; 
     for (int i=0; i!=size;i++)  
      tmp[i]=names1[i]; 
     names1=tmp; 
     names1[size]=line; 
    } 
} 
} 

不過上線names1=tmp;我得到

 
main.cpp:42:20: error: incompatible types in assignment of ‘std::string [(((unsigned int)(((int)(++ size)) + -0x000000001)) + 1)]’ to ‘std::string [0]’ 

...我是新的C++作爲一個javaguy,我真的很困惑:-S謝謝任何建議,如何解決這個問題..

+2

你的問題自相矛盾。標題中有'動態數組',但問題說你'必須使用靜態數組'。 – 2013-03-16 21:53:08

+0

數組不可分配。所以,如果你有一個數組''arr [N];'每次嘗試賦值'arr = whatever;'都會導致編譯錯誤。 – 2013-03-16 22:00:49

+1

每當我在同一個句子中看到(或聽到)「動態」和「數組」這個詞,我想'std :: vector'。 – 2013-03-16 22:04:00

回答

2

變量names1是一個包含零條目的數組(本身存在問題),並且您嘗試將該變量分配給單個字符串。這不會工作,因爲字符串數組不等於字符串。我建議你使用std::vector而不是零大小的數組。

要繼續,您不需要逐個字符複製到字符一個臨時變量,只需添加讀串入載體:

std::vector<std::string> names1; 

// ... 

while (std::getline(myfile, line)) 
    names1.push_back(line); 

如果您不能使用std::vector那麼你必須分配與更多比零條目適當的陣列。如果你超過了那個,那麼你必須重新分配這個來增加數組的大小。

喜歡的東西:

size_t current_size = 1; 
std::string* names1 = new std::string[current_size]; 

size_t line_counter = 0; 
std::string line; 
while (std::getline(myfile, line)) 
{ 
    if (line_counter > current_size) 
    { 
     std::string* new_names1 = new std::string[current_size * 2]; 
     std::copy(names1, names1 + current_size, new_names1); 
     delete[] names1; 
     names1 = new_names1; 
     current_size *= 2; 
    } 
    else 
    { 
     names1[line_counter++] = line; 
    } 
} 
+0

@JesseGood更新了我的答案有一個_dynamic_數組解決方案,但如果OP真的想要一個_static_數組,那麼OP將不得不找出他/她自己。 – 2013-03-16 22:13:54

+0

Ty ...這就是我一直在尋找:)我不是說靜態像對象修飾符,但我不知道,如何解釋,我不想使用矢量,但數組... ...在你的解決方案,在'std:copy'函數中有一個小錯誤,第三個參數應該是'new_names1' ...但無論如何 - 非常感謝:) – Dworza 2013-03-16 22:28:49