多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

C++学习日记 Day17:STL-函数对象+内建函数对象+常用算法

C++学习日记 Day17:STL-函数对象+内建函数对象+常用算法 ## 今天学了什么今天学习C中STL-函数对象、内建函数对象以及STL的一些常用算法。## 函数对象定义重载函数调用操作符的类其对象成为函数对象函数对象使用重载的时行为类似函数调用也叫做仿函数。本质函数对象是一个类不是函数。函数对象的使用在使用时可以向普通函数那样调用可以有参数可以有返回值可以有自己的状态函数对象可以作为参数传递## 谓词定义返回值是bool类型的仿函数。如果operator接收一个参数称为一元谓词两个参数称为二元谓词## 内建函数对象STL内建了一些函数对象分为算术仿函数、关系仿函数、逻辑仿函数头文件#includefunctional### 算术仿函数templateclass T negateT 取反仿函数templateclass T plusT 加仿函数templateclass T minusT 减仿函数templateclass T multipliesT 乘仿函数templateclass T dividesT 除仿函数templateclass T modulusT 取模仿函数用法示例negateintn;n(50) ;### 关系仿函数templateclass T bool equal_toT 等于仿函数templateclass T bool not_equal_toT 不等于仿函数templateclass T bool greaterT 大于仿函数templateclass T bool greater_equalT 大于等于仿函数templateclass T bool lessT 小于仿函数templateclass T bool less_equalT 小于等于仿函数### 逻辑仿函数templateclass T bool logical_andT 逻辑与仿函数templateclass T bool logical_orT 逻辑或与仿函数templateclass T bool logical_notT 逻辑非与仿函数## STL常用算法主要头文件 algorithm、functional、numeric等。①常用遍历算法for_each(v.begin(), v.end()val)transform(v.begin(), v.end(), v2.begin(), _func); //搬运* 注使用transform需要先指定v2容器的大小搬运时复制不是剪切。②常用查找算法vectorint::iterator itfind(v.begin(), v.end(), val); //返回迭代器vectorint::iterator it find_if(v.begin(), v.end(), _pred); //返回迭代器vectorint::iterator itadjacent_find(v.begin(), v.end()); // 查找相邻重复元素 返回迭代器bool retbinary_search(v.begin(), v.end(), val); // 二分查找 返回bool值int num count(v.begin(), v.end(), val);int num count_if(p.begin(), p.end(), _pred);* 注自定义类使用以上算法时需重载operator二分查找必须有序无序结果未知。③常用排序算法sortv.begin(), v.end(), _predmerge(v1.begin(), v1.end(), v2.begin(), v2.end(), vt.begin()); //合并两个有序容器并存到另一个容器中合并后容器仍有序reversev.begin(), v.end(); //反转random_shuffle(v.begin(), v.end()); //打乱顺序 C14已弃用
返回列表