2017-07-25 33 views
-6

我想從文件中讀取單詞並將它們存儲到向量中,但索引不起作用。讓它保持seg故障的原因是什麼?爲什麼push_back()起作用?使用索引和push_back()之間的機制差異是什麼?在向量中存儲字符串有seg故障

vector<string> readWordToArray(string fileName, int wordCount){ 
    vector<string> wordArray; 
    fstream inFile; 
    inFile.open(fileName); 
    string word; 
    int index = 0; 

    while(inFile >> word){ 
     // doesnt work, need to change to wordArray.push_back(word); 
     wordArray[index] = word; 
     index++; 
    } 
    return wordArray; 
} 
+5

你讀過['vector :: push_back'文檔](http://www.cplusplus.com/reference/vector/vector/push_back/)和['vector :: operator []'documentation](http://www.cplusplus.com/reference/vector/vector/operator [] /)並注意區別? –

回答

0

wordArray[index]是獲得一個現有的矢量元素的引用,我敢肯定,這是不確定的行爲使用這超出範圍的索引。

要添加一個到最後,你需要使用(如你在代碼中的註釋指出):

wordArray.push_back(word); 
+0

它需要的分配 – sam

+0

@sam,你在說什麼?這不是Java。向量和輸入字符串都在堆棧上構建,並且不需要分配。 – paxdiablo

-2

您應該分配您的載體。 vector.resize(int n)如果你想像一個數組一樣對待。否則,你必須使用Push_back()在向量的末尾分配新的內存。查看更多信息的鏈接enter link description here

+0

如果你想要一個數組,C++提供了數組。這樣做的問題在於,您將大小與容量綁定在一起。最好'push_back',以便大小始終代表集合中元素的數量。 – paxdiablo