关于bool

来源:百度知道 编辑:UC知道 时间:2024/06/30 03:45:56
#include<iostream>
using namespace std;
template<class elemtype>
int binarysearch(const elemtype list[],int length,const elemtype item);
int main()
{
int intlist[]={2,16,34,45,53,56,69,70,75,96};
int pos;
pos=binarysearch(intlist,10,45);
if(pos!=-1)
cout<<" * "<<45<<" found at position: "<<pos<<endl;
else
cout<<" * "<<45<<" is not in inlist"<<endl;
return 0;
}
template<class elemtype>
int binarysearch(const elemtype list[],int length,const elemtype item)
{
int first=0;
int last=length-1;
int mid;
bool found=true;
while(first<=last && !found)
{
mid=(first+last)/2;
if(list[mid]==item)
found=true;
else if(list[mid]>item)
last=mid-1;
else first =mid+1;
}
if(found)
return mid;
els

!found就是一个条件表达式,开始时本来就应该是true。去看看有关运算符的章节吧!

(found)是表示found==true ,但是!found并不表示未找到found。而是表示found==false时条件成立。

它们都只是一个判断条件,来判断查找到现在的状态。所以在刚开始的时候,当然是bool found=false,即:在最初没有找到。

否则bool found=true,while第一次条件!found就是false,不成立,循环就不会做!就是不会去查找。

这样,你返回的mid;就是未初始化的随机值。
是正是负都没有意义!

found=true表示已经找到要找的数据,初始值当然要是false。
!found不是表示未找到found,而是表示found不为真。也就是说没有找到。
你把found改成true,则一上来while里的条件就为假,就直接return mid了。mid没赋初值,所以实际打印出来的复制就是mid内存里的垃圾数据。你可以试下把mid的初始值设置为任意值,打印出来的必然是mid的值。