[英]Vector subscript out of range error, C++
當我嘗試運行此程序時,我收到一個錯誤,該程序暫停程序並說“向量下標超出范圍”
知道我做錯了什么嗎?
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
//(int argc, char* argv[]
int main()
{
fstream bookread("test.txt");
vector<string> words;
bookread.open("test.txt");
if(bookread.is_open()){
cout << "opening textfile";
while(bookread.good()){
string input;
//getline(bookread, input);
bookread>>input;
//string cleanedWord=preprocess(input);
//char first=cleanedWord[0];
//if(first<=*/
//cout << "getting words";
//getWords(words, input);
}
}
cout << "all done";
words[0];
getchar();
}
你永遠不會在單詞vector
插入任何東西,所以行words[0];
是非法的,因為它訪問它的第一個元素,它不存在。
我沒有看到你在向量上推送任何東西。 如果向量為空,則下標0將超出范圍。
看起來你的程序永遠不會向向量中添加任何內容,通常用push_back()
來完成,因此在運行時words[0]
會使你的subscript out of range
錯誤。
您應該在訪問之前檢查向量的大小。
嘗試這個:
for(vector<string>::const_iterator it=words.begin(), end=words.end(); it!=end; ++it){
cout << *it << ' ';
}
你能否附上你在矢量上實際push_back字符串的代碼版本。 除非可以查看重現的代碼,否則無法調試該問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.