这是我的功能:
void loadfromfile(string fn, vector<string>& file){
int x = 0;
ifstream text(fn.c_str());
while(text.good()){
getline(text, file.at(x));
x++;
}
//cout << fn << endl;
}
Run Code Online (Sandbox Code Playgroud)
我传入的fn的值只是文本文件的名称('10a.txt')我传入的文件的值声明如下:
vector<string> file1;
Run Code Online (Sandbox Code Playgroud)
我没有定义尺寸的原因是因为我不认为我必须使用矢量,它们是动态的......不是吗?
该函数应该读取给定的文本文件并将每行的全部内容存储到单个向量单元格中.
防爆.将第一行的内容存储到file.at(0)将第二行的内容存储到file.at(1)依此类推,直到文本文件中没有任何行.
错误:
在抛出'std :: out_of_range'的实例后调用终止what():vector :: _ M_range_check
我认为在while循环中检查应该可以防止这个错误!
在此先感谢您的帮助.
void binarysearch(string key, vector<string>& f2){
sort_vector(f2);
int mid = 0;
int left = 0;
int right = f2.size();
bool found = false;
while (left < right){
mid = left + (left+right)/2;
if (key > f2[mid]){
left = mid + 1;
}
else if(key < f2[mid]){
right = mid;
}
else{
found = true;
left = right;
}
}
cout << "out of while loop" << endl;
if (found == true){
cout << "YES: " << key << endl;
}
else{ …Run Code Online (Sandbox Code Playgroud)