注册 登录
编程论坛 C++教室

c++ primer中的一道练习题,有错误,请帮忙看看^-^

bczger 发布于 2014-03-13 23:16, 434 次点击
9.12 编写一个函数,其形参是一对迭代器和一个 int 型数值,实现在迭代器标记的范围内寻找该 int 型数值的功能,并返回一个 bool 结果,以指明是否找到指定数据。
这是原题目。我改进了下:自己输入vector的元素,回车结束输出。然后自己输入要找的数字。
结果不对,应该输入vector元素的时候错了吧。
程序代码:
#include <iostream>
#include <vector>
using namespace std;
bool find(vector<int>::iterator first,vector<int>::iterator last,int x)
{
    while(first!=last)
    {
        if(*first==x)
            return 1;
        first++;last++;
    }
    return 0;
}
void main()
{
    vector<int> vec;
    int ival;
    while(cin >> ival)
    {
        if(ival==(int)('\n'))
            break;
        vec.push_back(ival);
    }
    cout << "input the figure you want to find" << endl;
    int x;
    cin >> x;
    vector<int>::iterator fir = vec.begin();
    vector<int>::iterator las = vec.end();
    bool fin;
    fin=find(fir,las,x);
    if(fin)
        cout << "yes ,there is" << endl;
    else
        cout << "no,there isn't" << endl;
}

 
3 回复
#2
bczger2014-03-13 23:35
comeonbaby
#3
i802862014-03-14 10:29
第10行:last++是什么意思,这样做下标就越界了
在cin>>x前有必要让cin函数的标志位复位,并清一下缓存
无论哪一个标准的C++规范,都不存在这样的语句:void main()
#4
bczger2014-03-15 23:00
回复 3楼 i80286
真是感谢啊,这么耐心的,帮我找到错误了。
现在结果对了,我还想问问,怎么要用那么多回车
我的输入是2(空格)3(空格)(回车)ctrl+z(回车)(回车)
才能显示提示输入x。。
这是改过的程序。
程序代码:
#include <iostream>
#include <vector>
using namespace std;
bool find(vector<int>::iterator first,vector<int>::iterator last,int x)
{
    while(first != last)
    {
        if(*first == x)
            return 1;
        first++;
    }
    return 0;
}
int main()
{
    vector<int> vec;
    int ival;
    cout << "plz input the elements,print 'ctrl'+'z' to end"<<endl;
    while(cin >> ival)
        vec.push_back(ival);
    cout << "input the figure you want to find" << endl;
    int x;
    cin.clear();
    cin.sync();
    cin >> x;
    vector<int>::iterator fir = vec.begin();
    vector<int>::iterator las = vec.end();
    bool fin;
    fin = find(fir,las,x);
    if(fin)
        cout << "yes ,there is" << endl;
    else
        cout << "no,there isn't" << endl;
    return 0;
}

 
1