![](/img/trans.png)
[英]c++ primer 5th 1.4.4 why can't std::cout type out things immediately
[英]Why this C++ code(from C++ Primer 5th 3.4.2) can't work right?
#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;
}
該程序是自清除的。 Lemme知道您是否有任何問題。 我想這應該工作。
希望這可以幫助
看起來像是mid = beg + (end - beg) / 2;
是您問題的根源。 如果您要在while循環中開始工作,則應執行以下操作。
while(++mid != end && *mid != "l")
++mid
開始密鑰。
*mid
始終是循環中的“ a”。 這永遠不符合退出的條件。
while (mid != end && *mid != "l") {
if ("l" < *mid) {
end = mid;
} else {
beg = mid+1; //Increment mid here to exit the loop;
}
mid = beg + (end - beg) / 2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.