algorithm中提供了很多算法,但是当有容器成员函数和全局函数(算法)同时存在时,优先考虑使用同名的成员函数,如果没有同名的成员函数,才考虑使用这些算法
1.for_each(遍历)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void myfunc(int c)
{
cout << c << endl;
}
class A
{
public:
void operator()(int c)
{
cout << c << endl;
}
};
int main()
{
vector<int> vec = { 5,4,3,1,2 };
//第一种调用方法,第三个参数传入一个函数
for_each(vec.begin(), vec.end(), myfunc);
//第二种调用方法,第三个参数传入一个仿函数
for_each(vec.begin(), vec.end(), A());
//第三种调用方法,第三个参数传入一个lambda表达式
for_each(vec.begin(), vec.end(), [](int c) { cout<<c<<endl; });
return 0;
}
参考博客:C++仿函数 C++lambda表达式
2 find
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> vec = { 5,4,3,1,2 };
vector<int>::iterator finditer = find(vec.begin(), vec.end(), 400); //判断是否等于find的第二个参数,等于就没找到,不等于就找到了
if (finditer != vec.end())
{
cout << "找到了" << endl;
}
else
{
cout << "没找到" << endl;
}
return 0;
}
3 find_if
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> vec = { 5,4,3,1,2 };
vector<int>::iterator finditer = find_if(vec.begin(), vec.end(), [](int c)
{
if (c < 3)
return true;
return false;
});
if (finditer != vec.end())
{
cout << "找到了:" <<*finditer<< endl;
}
else
{
cout << "没找到" << endl;
}
return 0;
}
4 sort(仅支持包含随机访问迭代器的容器,例如vector)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool myfunc(int i, int j)
{
if (i < j)
return true;
return false;
}
int main()
{
vector<int> vec = { 5,4,3,1,2 };
sort(vec.begin(), vec.end(), myfunc);
for_each(vec.begin(), vec.end(), [](int c) {cout << c << endl; });
return 0;
}
5 补充
algorithm中提供了很多算法,但是当有容器成员函数和全局函数(算法)同时存在时,优先考虑使用同名的成员函数,如果没有同名的成员函数,才考虑使用这些算法