读书人

容器查询有关问题

发布时间: 2012-04-05 12:42:39 作者: rapoo

容器查询问题

C/C++ code
#include <iostream>#include <vector>/****为什么查不了?****/using namespace std;bool intReturn(vector<int>::iterator it, vector<int>::iterator iter, int num){    while(it != iter)    {        if(*it == num)        {            return true;        }        else        {            return false;        }        ++it;    }}int main(){    vector<int> text;    int word;    while(1)    {        cin >> word;        if(word == 0)        {            break;        }        text.push_back(word);    }    int number;    cout << "输入要查询的整数: ";    cin >> number;    vector<int>::iterator it = text.begin();    vector<int>::iterator iter = text.end();    bool vec;    vec = intReturn(it, iter, number);    if(vec == true)    {        cout << "查找到了" << endl;    }    else    {        cout << "没有这个数" << endl;    }    return 0;}


[解决办法]
逻辑错了
while(it != iter)
{
if(*it == num)
{
return true;
}
else
{
return false;
}
++it;
}
else部分要去掉,最外层return false
自己单步调试一下就知道了
[解决办法]
像这样改
bool intReturn(vector<int>::iterator it, vector<int>::iterator iter, int num)
{
bool i=0;
while(it != iter)
{
if(*it == num)
{
i=1;
return i;
}

++it;
}
}

读书人网 >C++

热点推荐