2017-07-25 66 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