| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 434 人关注过本帖
标题:c++ primer中的一道练习题,有错误,请帮忙看看^-^
只看楼主 加入收藏
bczger
Rank: 2
等 级:论坛游民
帖 子:13
专家分:11
注 册:2013-4-21
结帖率:100%
收藏
已结贴  问题点数:10 回复次数:3 
c++ primer中的一道练习题,有错误,请帮忙看看^-^
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;
}

 
搜索更多相关主题的帖子: 练习题 元素 
2014-03-13 23:16
bczger
Rank: 2
等 级:论坛游民
帖 子:13
专家分:11
注 册:2013-4-21
收藏
得分:0 
comeonbaby
2014-03-13 23:35
i80286
Rank: 6Rank: 6
等 级:侠之大者
威 望:5
帖 子:99
专家分:428
注 册:2013-9-30
收藏
得分:10 
第10行:last++是什么意思,这样做下标就越界了
在cin>>x前有必要让cin函数的标志位复位,并清一下缓存
无论哪一个标准的C++规范,都不存在这样的语句:void main()
2014-03-14 10:29
bczger
Rank: 2
等 级:论坛游民
帖 子:13
专家分:11
注 册:2013-4-21
收藏
得分:0 
回复 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;
}

 
2014-03-15 23:00
快速回复:c++ primer中的一道练习题,有错误,请帮忙看看^-^
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015553 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved