文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>查找容器中的元素

查找容器中的元素

时间:2010-12-21  来源:longmenyu

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<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;
}*/

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<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;
    }*/


    /*读入要找的数据*/
    cout<<"Please input a integer:";
    int ival;
    cin>>ival;
// cout<<endl;

 
    /*调用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.


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载