概述:
算法主要是由头文件<algorithm><functional><numeric>组成
<algorithm>是所有STL头文件中最大的一个 范围涉及到比较、交换、查找、遍历操作、复
制、修改等
<numeric>体积很小 只包括几个在序列上面进行简单数学运算的模版函数
<functional>定义了一些模版类 用以声明函数对象
常用遍历算法
for_each //遍历容器
transform //搬用容器到另一个容器中
for_each:
函数原型:for_each(iterator beg, iterator end, _func);
//beg 开始迭代器
//end 结束迭代器
//_func 函数或函数对象
注意⚠️:普通函数放入的是函数名
仿函数要把匿名的函数对象放进来 所以加了()
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
//普通函数
void print01(int val){
cout << val << " ";
}
//仿函数
class print02{
public:
void operator()(int val){
cout << val << " ";
}
};
void test01()
{
vector<int>v;
//插入数据0~9
for(int i=0; i<10; i++){
v.push_back(i);
}
//普通函数放入的是函数名
for_each(v.begin(), v.end(), print01);
cout << endl;
//仿函数要把匿名的函数对象放进来 所以加了()
for_each(v.begin(), v.end(), print02());
cout << endl;
}
int main() {
test01();
return 0;
}
输出结果:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
transform:
函数原型:transform(iterator beg1, iterator end1, iterator beg2, _func);
//beg1 源容器开始迭代器
//end1 源容器结束迭代器
//beg2 目标容器开始迭代器
//_func 函数或函数对象
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
//搬运仿函数
class Tansform
{
public:
//这里的搬运相当于把每一个int数据从源容器拿出来再返回到目标容器
int operator()(int v){
//这里v+100就相当于在搬运过程中每个元素数据加了100放入目标容器
return v+100;
}
};
//遍历仿函数
class MyPrint
{
public:
void operator()(int val){
cout << val << " ";
}
};
void test01()
{
//源容器
vector<int>v;
//插入数据0~9
for(int i=0; i<10; i++){
v.push_back(i);
}
//目标容器
vector<int>vTarget;
//目标容器必须提前开辟容量空间 不然放不进去
vTarget.resize(v.size());
//开始搬运操作
transform(v.begin(), v.end(), vTarget.begin(), Tansform());
//开始遍历操作
for_each(vTarget.begin(), vTarget.end(), MyPrint());
cout << endl;
}
int main() {
test01();
return 0;
}
输出结果:
100 101 102 103 104 105 106 107 108 109
常用查找算法
find //查找元素
find_if //按条件查找元素
adjacent_find //查找相邻重复元素
binary_search //二分查找法
count //统计元素个数
count_if //按条件统计元素个数
find:
功能:查找指定元素 找到返回指定元素的迭代器 找不到返回结束迭代器end()
函数原型:find(iterator beg, iterator end, value);
//beg 开始迭代器
//end 结束迭代器
//value 查找的元素
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include <string>
//查找内置的