2017-03-03 312 views
0

爲什麼push_back無法正常工作?很困惑,爲什麼它不與下面vector push_back無法正常工作C++

using namespace std; 
void addItem(vector<string>& STRING, string item) 
{ 
    STRING.push_back(item); 
} 

int main() 
{ 
    string item; 
    vector<string> STRING(100); 
    ifstream myFile; 
    myFile.open("food.txt"); 

    if (myFile.is_open()) //code where I store my data into the array 
    { 
     int i = 0; 
     while (!myFile.eof()) 
     { 
      getline(myFile, STRING[i]); 
      i++; 
     } 
    } 
    myFile.close(); 

    cin >> item; 
    addItem(STRING, item); 
    int x = 0; 
    while(!STRING[x].empty()) //code to print the current array 
    { 
     cout << STRING[x]; 
     printf("\n"); 
     x++; 
     return 0; 
    } 
} 

我當前的代碼的工作有什麼錯我是如何初始化我的數組?因爲當我使用CodeBlocks時,有0個錯誤和0個警告,所以我認爲它很好,直到我運行它。

+6

請提供一個[MCVE],我們可以重現該問題。 –

+1

如果您的'printList'是您在最小代碼中顯示的while循環,那麼這顯然是錯誤的。此外,你從來沒有真正檢查矢量的長度是否發生了變化,所以你怎麼確定它沒有? – UnholySheep

+0

重構您的代碼,使得數字100在任何地方都不被硬編碼。將'STRING'初始化爲空,並使用'push_back'從頭開始添加。將該變量重命名爲'strings',因爲'STRING'看起來像一個宏。在循環條件下不要使用'eof'。最後,避免使用名稱空間標準;哦,考慮'std :: cout'而不是'printf'。 –

回答

2

您的代碼確實有效。但是,您在創建時指定了矢量的初始大小。你的向量以100個元素的初始大小開始。據說,你的確在給數組添加新的元素,但是push_back()將它放在已經存在的數組之後 - 在第100個位置。

您可以通過使用defaul構造

vector<string> STRING; 

而且避免它,我會在這裏貼上我的printList功能,會告訴你是什麼問題有:

void printList(vector<string> &STRING) 
{ 
    cout << "size: " << STRING.size() << endl; 
    for (int i = 0; i < STRING.size(); i++) 
     cout << i << ":" << STRING[i] << ", "; 
    cout << endl; 
} 

@編輯:修正語法錯誤(矢量而不是矢量)。感謝您指出Christian Hackl!

+0

whoo thanks dude your printList function works,now I'll see the problem –

+0

在你的回答中有一個錯字,它表示'Vector'而不是'vector'。你應該使用''n''而不是'std :: endl'。 –

+0

@ChristianHackl修復了錯字,感謝您指出!你能詳細說明'\ n'而不是std :: endl部分嗎?我所知道的所有差異都是關於std :: endl每次使用的刷新輸出(如果過度使用,則會降低性能)。 – Kosmo