#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<string> text = {"a", "v"};
vector<string>::iterator beg = text.begin();
vector<string>::iterator end = text.end();
vector<string>::iterator mid = text.begin() + (end - beg) / 2;
while (mid != end && *mid != "l") {
if ("l" < *mid) {
end = mid;
} else {
beg = mid;
}
mid = beg + (end - beg) / 2;
}
if (*mid == "l")
cout << "Have Found!" << endl;
else
cout << "Not Found!" << endl;
return 0;
}
我不知道为什么会死循环?请帮助我!我在 VisulStudio 2013 和 Code::Block 中构建代码,但结果都是不好的!
最佳答案
好吧,我正在抓紧解决方案,因为我认为您的算法出错了,这使得 mid
指向未识别的位置。我发现您使用的是 C++11
。不过,这个解决方案可以正常工作。
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void populateVector(vector<string> &text)
{
for(int i=97;i<=118;i++)
{
text.push_back(string(1,(char)i));
}
}
void printVector(vector<string> &text)
{
for(int i=0;i<text.size();i++)
{
cout<<text[i]<<"\n";
}
}
bool found(vector<string> &text,string &toBeFound)
{
vector<string>::iterator beg = text.begin();
vector<string>::iterator end = text.end();
vector<string>::iterator mid ;
while(beg<=end)
{
mid = beg + (end - beg) / 2;
//This piece of code had to be added
if(mid==end)
{
break;
}
//This piece of code had to be added
//@DEBUG: cout<<*mid<<"\n";
if(*mid==toBeFound)
{
return true;
}
if(*mid<toBeFound)
{
beg=mid+1;
}
else
{
end=mid-1;
}
}
return false;
}
int main()
{
vector<string> text;
string toBeFound = "l";
populateVector(text);
printVector(text);
if(found(text,toBeFound))
{
cout<<"Found\n";
}
else
{
cout<<"Not Found\n";
}
return 0;
}
程序是自清的。如果您有任何问题,请告诉我。我想这应该可行。
希望对你有帮助
关于c++ - 为什么这个 C++ 代码(来自 C++ Primer 5th 3.4.2)不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28921379/