我希望从文件中获取一些Integer,然后从用户那里获取一个数字,但是当代码到达从用户程序提供数字的行停止工作并退出 这是我的代码
#include <iostream>
#include <bits/stdc++.h>
#include <vector>
#include <fstream>
using namespace std;
void mysort(vector<int>& beep) //this is for sorting vector has no problem
{
int temp;
for (int i = 1; i < beep.size(); i++) {
if (beep[i - 1] > beep[i]) {
temp = beep[i];
beep[i] = beep[i - 1];
beep[i - 1] = temp;
}
}
}
int mysearch(vector<int>& beep, int x, int top, int bot) //and this is not problem too
{
int mid = (top - bot +1) / 2;
if (x == beep[mid])
return mid;
else if (x > beep[mid])
return mysearch(beep, x, beep.size(), mid + 1);
else
return mysearch(beep, x, mid - 1, 0);
}
void myprint(vector<int>& beep) //and this is for printing have no problem
{
for (int i = 0; i < beep.size(); i++)
cout << beep[i] << " ";
}
int main()
{
vector<int> beep;
ifstream in;
in.open("input.txt");
int x;
while (in >> x) {
beep.push_back(x);
}
in.close();
mysort(beep);
int l;
cout << "this is sorted array: " << endl;
myprint(beep);
cout << endl;
cout << "enter which one you looking for: ";
cin >> l; //this is where problem begins
cout << mysearch(beep, l, beep.size(), 0);
return 0;
}
在问题所在的cin>>l
中,程序停止工作。
答案 0 :(得分:1)
你的问题不在于cin&gt;&gt;升;
问题出在你的mysearch功能中。
你的算法错了。
在二进制搜索中,您不能使用向量的方法大小。相反,你应该使用top和bot(在你的代码中)。你的功能还有其他问题。
查看此代码。
int search (int x, int v[], int left, int right)
{
int i = (left + right)/2;
if (v[i] == x)
return i;
if (left >= right)
return -1;
else
if (v[i] < x)
return search(x, v, i+1, right);
else
return search(x, v, left, i-1);
}