Chinaunix首页 | 论坛 | 博客
  • 博客访问: 119619
  • 博文数量: 29
  • 博客积分: 1215
  • 博客等级: 中尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-05 16:29
文章分类
文章存档

2010年(29)

我的朋友

分类: C/C++

2010-12-21 01:23:58

1.编写一个函数,其形参是一对迭代器和一个int型数值,实现在迭代器标记的范围内寻找该int型数值的功能,并返回一个bool结果,以指明是否找到指定数据(《C++ Primier》习题9.12)。

程序清单:

#include <iostream>
#include <vector>

using namespace std;

bool findElement(vector<int>::iterator beg,
                 vector<int>::iterator end,
                 int elem)
{
    for(vector<int>::iterator ivec = beg; ivec != end; ivec++)
    {
        if(elem == *ivec)
        {
            return true;
        }
    }
    return false;
}

int main(int argc,char *argv[])
{
    bool flag;
    int ia[] = {0,1,2,3,4,5,6,7,8,9};
    vector<int> ivec(ia,ia+10);
    vector<int>::iterator ibeg = ivec.begin();
    vector<int>::iterator iend = ivec.end();
    flag = findElement(ibeg,iend,6);
    if(true == flag)
    {
         cout<<"Find element!"<<endl;
    }
    else
    {
        cout<<"Didn't find element!"<<endl;
    }
    return 0;
}

执行结果:
Find element!

2.重写上面的程序,查找元素的值,并返回找到的元素的迭代器。确保程序在要寻找的元素不存在时也能正常工作。(《C++ Primier》习题9.13)

程序清单:


#include <iostream>
#include <vector>

using namespace std;
/*
bool findElement(vector::iterator beg,
                 vector::iterator end,
                 int elem)
{
    for(vector::iterator ivec = beg; ivec != end; ivec++)
    {
        if(elem == *ivec)
        {
            return true;
        }
    }
    return false;
}*/


vector<int>::iterator findElement(vector<int>::iterator beg,
                                  vector<int>::iterator end,
                                  int ival)
{
    while(beg != end)
    {
         if(*beg ==ival)
             break;
         else
             ++beg;
    }
    return beg;
}


int main(int argc,char *argv[])
{
 // bool flag;

    int ia[] = {0,1,2,3,4,5,6,7,8,9};
    vector<int> ivec(ia,ia+10);
/* vector::iterator ibeg = ivec.begin();
    vector::iterator iend = ivec.end();
    flag = findElement(ibeg,iend,6);
    if(true == flag)
    {
         cout<<"Find element!"<     }
    else
    {
        cout<<"Didn't find element!"<     }*/



    /*读入要找的数据*/
    cout<<"Please input a integer:";
    int ival;
    cin>>ival;
// cout<
 
    /*调用findElement函数查找ival*/
    vector<int>::iterator it;
    it = findElement(ivec.begin(),ivec.end(),ival);
    if(it != ivec.end())
        cout<<ival<<" is a element of the vector."<<endl;
    else
        cout<<ival<<" isn't a element of the vector."<<endl;
    return 0;
}

程序执行结果:
Please input a integer:6
6 is a element of the vector.



阅读(2237) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-12-22 14:19:46

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com