C++ 泛型算法

一、泛型算法的基本概念


所有容器类型的公共操作,组成的泛型算法集合,能够被应用到容器类型以及内置数组上。
所需的头文件是:#include <algorithm>

二、泛型算法中的find与内置数组

以下实例实现了使用find查找并且返回数组中的元素地址:

#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>
using namespace std;

int main()
{
    int int_array[10];
    int array_len = sizeof (int_array) / sizeof (int);
    /*获取随机值*/
    srand(time(0));
    for(int n=0; n<array_len; n++)
    {
        int_array[n] = rand()%100;
    }

    /*对数组进行显示*/
    cout<<"对一下数据进行检索:";
    for(int n=0; n<array_len; n++)
    {
        cout<<int_array[n]<<" ";
    }
    cout<<endl;

    int find_data;
    while(1)
    {
        cout<<"请输入要检索的数据:";
        cin>>find_data;
        /*进行检索*/
        int * obj_data_p =find(int_array,int_array+array_len,find_data);
        if(obj_data_p != int_array+array_len)
        {
            cout<<"检索成功!\n"<<endl;
        }
        else
        {
            cout<<"检索失败!\n"<<endl;
        }
    }

    return 0;
}

运行结果:

对一下数据进行检索:90 94 74 81 34 63 81 20 72 34
请输入要检索的数据:343
检索失败!

请输入要检索的数据:90
检索成功!

请输入要检索的数据:55
检索失败!

请输入要检索的数据:72
检索成功!

请输入要检索的数据:

三、泛型算法中的find与vector

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string s_array[] = {"dante","vivian"};


    vector <string> vs(s_array,s_array+2);

    string find_data;

    while(1)
    {
        cout<<"请输入要检索的数据:";
        cin>>find_data;
        vector<string>::iterator obj_data_p =  find(vs.begin(),vs.end(),find_data);

        if(obj_data_p != vs.end())
        {
            cout<<"查找成功!\n"<<endl;
        }
        else
        {
            cout<<"查找失败!\n"<<endl;
        }
    }

    return 0;
}

运行结果:

请输入要检索的数据:dante
查找成功!

请输入要检索的数据:sd
查找失败!

请输入要检索的数据:vivian
查找成功!

请输入要检索的数据:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值