算法概述
可以理解为函数模板。比如:查找、排序等,有数十上百个算法,前两个参数一般都是迭代器类型,表示容器中的元素的一个区间
调用方式:算法名(iterbg,itered)传递进去的应该是前闭后开的区间 [ begin() , end() ] ;
好处:
a、如果第一个形参等于第二个形参,也就是 iterbg == itered, 那么就表示是个空区间;
b、迭代时,算法判断迭代器只要等于最后变这个开区间,那么就表示迭代结束;
算法:一种搭配迭代器使用的全局函数;算法跟具体容器没关联,只跟迭代器有关联;只需要根据迭代器来开发算法,不需要理会具体容器。这种方式更加灵活,但是也缺失了直观性;某些数据结构和算法之间的兼容性也不那么好
算法的一些内部处理
算法会根据传递进来的迭代器来分析出迭代器的种类,不同种类的迭代器,算法会有不同的处理,要编写不同的代码来应对;
这种辨析不同代码来处理不同种类迭代器,能够直接影响到算法的执行效率;
这也是STL内部为什么要做一个分类的目的;
一些算法使用范例
算法头文件要包含进来:#include <algorithm>
1、for_each()
void myfunc(int i){
cout << i << endl;
}
vector<int> myvec{ 10, 20, 30, 40 };
for_each(myvec.begin(), myvec.end(), myfunc); //myfunc是一个可调用对象
2、find()
vector<int> myvec{ 10, 20, 30, 40 };
vector<int> finder = find(myvec.begin(), myvec.end(), 40); //myfunc是一个可调用对象
if (finder != myvec.end()){ //判断是否等于find的第二个参数,等于就没找到,不等于就找到了
cout << "find it" << endl;
}
当成员函数和全局函数同时存在时,优先考虑使用同名的成员函数,如果没有成员函数在考虑使用全局函数。
map<int, string> mymap;
mymap.push_back(2, "li");
mymap.push_back(1, "bai");
auto finder = mymap.find(2);
if (finder != mymap.end()){
printf("id:%d, name:%s", iter->first, iter->second.c_str());
}
3、find_if()
auto result = find_if(myvec.begin(), myvec.end(), [](int val)
{
if (val > 15){
return true;
}
return false;
}
);
if (result == myvec.end()){
cout << "not find" << endl;
}
else{
cout << "find it" << endl;
}
4、sort()
vector<int> myvec = { 50, 15, 80, 30};
sort(myvec.begin(), myvec.end()); //缺省参数时按照从小到大排列
可以自定义排序
bool func(int i, int j){
return i < j; //从小到大排序
}
bool func(int i, int j){
return i < j; //从大到小排序
}
sort(myvec.begin(), myvec.end(), func);