一、泛型算法的基本概念
所有容器类型的公共操作,组成的泛型算法集合,能够被应用到容器类型以及内置数组上。
所需的头文件是:#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
查找成功!
请输入要检索的数据: