一. 泛型算法
1. 前言
泛型算法:可以支持多种类型的算法
此处主要来讨论怎么使用标准库中定义的泛型算法<algorithm>
, numeric
, ranges
. 在引入泛型算法之前,还有一种是方法的形式,比如说std::sort
和std::list::sort
,前者是算法,后者是list类中定义的函数(方法)
为什么引入泛型算法,而不用方法的形式?
- c++内建数据类型不支持方法(如int,float等,vector可以)
- 计算逻辑存在相似性,避免重复定义
但如果有方法和泛型算法同名,功能类似时,建议使用方法,比如std::find
和std::map::find
,即只要类里面提供了这个方法就使用,因为一般这个类中的方法可以针对此类有更好的优化。
2. 泛型算法的分类
读:给定迭代空间,读其中的元素并进行计算。举例:std::accumulate
, std::find
, std::count
写:向一个迭代区间中写入元素,一定要保证写入的目标区间的大小足够(后续也会提到怎么给目标区间动态扩充)。 举例:
- 单纯写:
std::fill
(直接给结果idx),std::fill_n
(给的count数) - 读+写:
std::transform
(一般可以对一个vector做某种运算后存入新vector),std::copy
排序:改变输入序列中元素的顺序。举例:std::sort
,std::unique
(去除相邻的重复元素,使用前需要对数组进行排序,且会把重复的元素放到数组的最后面,这个用于区分的索引是unique的返回值,可以之后erase掉)
3. 迭代器的种类*(catagory)
*了解即可,和迭代器的类型不同,比如int*可以作为一种类型。一般,根据不同的迭代器种类,会有不同的优化算法
- 输入迭代器:可读,可递增
- 输出迭代器:可写,可递增
- 前向迭代器:可读写,可递增
- 双向迭代器:可读写,可递增递减
- 随机访问迭代器:可读写,可递减一个整数
4. 特殊迭代器
-
插入迭代器:back_insert_iterator, front_insert_iterator, insert_iterator
-
流迭代器: istream_iterator, ostream_iterator
#include <iterator> #include <sstream> int main() { std::istringstream str("1 2 3 4 5"); std::istream_iterator<int> x(str); std::istream_iterator<int> y{ }; //流迭代器中,用此表示结束 for(; x!=y; ++x) { std::cout << *x << std::endl; //可以依次打印出12345 } }
#include<vector> #include <iterator> #include <numeric> #include <sstream> int main() { std::vector<int> x{ 1,2,3,4,5}; std::copy(x.rbegin(), x.rend(), std::ostream_iterator<int>(std::cout, " ")); //打印结果为”5 4 3 3 1 “ }
-
反向迭代器
-
移动迭代器:move_iterator
5.并发算法
std::execution::seq 顺序执行
std::execution::par 并发执行
std::execution::par_unseq 并发非顺序执行
std::execution::unseq
二. bind和lambda表达式
1. 可调用对象
类似于sort算法中,用来定义sort规则的那个部分
- 函数指针:概念直观但定义位置受限
- 类:功能强大但书写麻烦
- bind:基于已有的逻辑灵活适配,但复杂逻辑时语法会难懂
- lambda:小巧灵活,功能强大
2. bind
早期的bind1st和bind2nd
#include <functional>
bool MyPredict(int val)
{
return val >3;
}
int main()
{
std::vector<int> x{
1,2,3,4,5,6,7,8,9,10};
std::vector<int> y;
std::copy_if(x.begin(), x.end(), std::back_inserter(y), std::bind1st(std::greater<int>(), 3)); //打印出的为1,2
std::copy_if(x.begin(), x.end(), std::back_inserter(y