技术在于交流、沟通,本文为博主原创文章转载请注明出处并保持作品的完整性

介绍11种STL标准库的算法,从这11种算法中总结一下算法的基本使用

1.accumulate() 累加

2.for_each() for一段区间 做你指定的行为

3.replace(), replace_if(), replace_copy() 替换函数

4.count(), count_if() 计数

5.find() 查找

6.sort() 排序

7.binary_search()查看元素是否在指定区间


下面的仿函数都没有继承自 binary_function<T,T,bool>, unary_function<T,bool>,但是在实际操作中,声明仿函数一定要继承自binary_function<T,T,bool>,unary_function<T,bool>

下一节内容会介绍为什么要继承自这两个类


一 accumulate(),累加,将指定区域内的value累加起来

源码及参数介绍

//默认累加算法,将传进的__first(begin()迭代器)位置,至__last(end()迭代器),与init求和
template<typename _InputIterator, typename _Tp>
inline _Tp
accumulate(_InputIterator __first, _InputIterator __last, _Tp __init)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first)
__init = __init + *__first;
return __init;
} //自定义accumulate 按照指定的要求做”累加”操作
template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
inline _Tp
accumulate(_InputIterator __first, _InputIterator __last, _Tp __init,
_BinaryOperation __binary_op)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_requires_valid_range(__first, __last); for (; __first != __last; ++__first)
__init = __binary_op(__init, *__first);
return __init;
}

基本使用

#include <iostream>
#include <functional>
#include <numeric>
#include <vector>
#include <algorithm>
using namespace std; namespace wzj000 {
int myfunc(int x, int y) {return x+*y;} struct myclass{
int operator()(int x, int y){return x+*y;}
}; void test_accumulate()
{
int init = ;
int num[] {, , }; cout<<"default accumulate: " << accumulate(num, num+, init)<< endl; //100 + 10 + 20 + 30 默认累加 cout << "using minus: " << accumulate(num, num+, init, minus<int>())<< endl; //100 - 10 - 20 - 30 将累加改为递减 cout << "using custom function: " << accumulate(num, num+, init, myfunc)<< endl; // 100 + 2*10 + 2*20 + 2*30 自定义"累加"规则 func cout << "suing custom object: " << accumulate(num, num+, init, myclass())<< endl; // 100 + 3*10 + 3*20 + 3*30自定义"累加"规则 仿函数
}
}

测试结果


二 for_each()  for一段区间 做你指定的行为

源码及参数介绍

template <class Inputerator, class Function>
Function for_each(Inputerator first, Inputerator last, Function f)
{//参数1 起始点 参数2 终点, 参数3 想要执行的操作
for( ; first != last; ++first)
{
f(*first);
}
return f;
}

基本使用

namespace wzj001 {
void myfunc(int i)
{
cout << " - " << i;
} struct myclass{
void operator()(int i)
{
cout << " ^ " << i;
}
}; void test_for_each()
{
vector<int> myVector = {, , };
for_each(myVector.begin(), myVector.end(), myfunc);
cout << endl;
} void test_for_each_classFunc()
{
vector<int> myVector = {, , };
for_each(myVector.begin(), myVector.end(), myclass());
cout << endl;
}
}

测试结果


三 replace() 替换函数

replace_if()

   replace_copy()

源码及参数介绍

template <class ForwardIterator, class T>
void replace(Inputerator first, Inputerator last, const T & old_value, const T& new_value)
{//范围内所有等于old_value者都一new_value取代
for( ; first != last; ++first)
{
if(*first == old_value)
*first = new_value;
}
} template <class Inputerator, class Inputerator, class T>
void replace_if(ForwardIterator first, ForwardIterator last, Predicate pred, const T& new_value)
{//范围内所有满足pred()为true之元素都以new_value取代
for( ; first != last; ++first)
{
if(pred(*first))
*first = new_value;
}
} template <class Inputerator, class Outputerator, class T>
Outputerator replace_copy(ForwardIterator first, ForwardIterator last, Outputerator result, const T & old_value, const T& new_value)
{//范围内所有等于old_value者都以new_value放置新区域
//不符合者原值放入新区域
for( ; first != last; ++first, ++result)
{
*result = *first == old_value ? new_value : *first;
}
}

基本使用

namespace wzj002 {
struct myclass{
bool operator()(int i)
{
return i >= ? true : false;
}
}; void test_replace()
{
vector<int> myVector = {, , };
replace(myVector.begin(), myVector.end(), ,);
cout << "replace: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
} void test_replace_if()
{
vector<int> myVector = {, , };
replace_if(myVector.begin(), myVector.end(), myclass(), );
cout << "replace_if: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
} void test_replace_copy()
{
vector<int> myVector = {, , };
vector<int> myNewVector;
myNewVector.resize();
replace_copy(myVector.begin(), myVector.end(), myNewVector.begin(), , );
cout << "replace_if_New: ";
for(auto i : myNewVector)
{
cout << i << " ";
}
cout << endl; cout << "replace_if_Old: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
}
}

测试结果


四 count() 计数

count_if()

源码及参数介绍

template <class Inputerator, class Outputerator, class T>
typename iterator_traits<Inputerator>::difference_type;
count(Inputerator first, Inputerator last, const T& value)
{
typename iterator_traits<Inputerator>::difference_type;
for( ; first != last; ++first)
if(*first == value) //满足要求 值 == value 累计+1
++n;
return n;
} template <class Inputerator, class Outputerator, class Predicate>
typename iterator_traits<Inputerator>::difference_type;
count_if(Inputerator first, Inputerator last, Predicate pred)
{
typename iterator_traits<Inputerator>::difference_type;
for( ; first != last; ++first)
if(pred(*first)) //满足指定要求 累计 +1
++n;
return n;
}

count()和count_if()是全局算法,适用于array,vector,list,forward_list, deque

map,set,unordered_set/map由于是关联式容器,所有有自己的count()和count_if()函数

基本使用

namespace wzj003 {
struct myclass{
bool operator()(int i)
{
return i >= ;
}
}; void test_count()
{
vector<int> myVector = {, , };
cout << "count(): "<< count(myVector.begin(), myVector.end(), ) <<endl;
} void test_count_if()
{
vector<int> myVector = {, , , , , };
cout << "count_if(): " << count_if(myVector.begin(), myVector.end(), myclass()) <<endl;
}
}

测试结果


五 find() 查找

  find_if()

find()和find_if()是全局算法,适用于array,vector,list,forward_list, deque

map,set,unordered_set/map由于是关联式容器,所有有自己的find()和find_if()函数

源码及参数介绍

template <class Inputerator, class T>
Inputerator find_if(Inputerator first, Inputerator last, const T& value)
{
while(first != last && *first != value)
++first;
return first;
} template <class Inputerator, class Predicate>
Inputerator find_if(Inputerator first, Inputerator last, Predicate pred)
{
while(first != last && !pred(*first))
++first;
return first;
}

基本使用

namespace wzj004 {
struct myclass{
bool operator()(int i)
{
return i >= ;
}
}; void test_find()
{
vector<int> myVector = {, , };
auto tmp = find(myVector.begin(), myVector.end(), );
cout << "find(): "<< distance(myVector.begin(), tmp) <<endl;
} void test_find_if()
{
vector<int> myVector = {, , };
auto tmp = find_if(myVector.begin(), myVector.end(), myclass());
cout << "find_if(): " << distance(myVector.begin(), tmp)<<endl;
}
}

测试结果


六 sort 排序

list和forward_list有成员sort()函数

set/map自动排序

array,vector,deque用全局sort()

namespace wzj005 {
struct myclass{
bool operator()(int i, int y)
{
return i > y;// sort默认降序, 自定义为升序
}
}; void test_sort()
{
vector<int> myVector = {, , , , , , , , };
sort(myVector.begin(), myVector.end());
cout << "sort: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl; } void test_sort_if()
{
vector<int> myVector = {, , , , , , , , };
sort(myVector.begin(), myVector.end(), myclass());
cout << "sort_if: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
}
}

测试结果


七 binary_search()查看元素是否在指定区间内

源码及参数介绍

template <class Inputerator, class T>
bool binary_search(Inputerator first, Inputerator last, const T& val)
{//返回元素是否在指定区间
first = std::lower_bound(first,last,val);
return (first != last && !(val < *first));
}

基本使用

namespace wzj006 {
struct myclass{
bool operator()(int i, int y)
{
return i > y;
}
}; void test_binary_search()
{
vector<int> myVector = {, , , , , , , , };
cout <<"binary_search: " << (binary_search(myVector.begin(), myVector.end(), ) ? "true" : "false") << endl;
}
}

测试结果

全部测试代码

#include <iostream>
#include <functional>
#include <numeric>
#include <vector>
#include <algorithm>
using namespace std; namespace wzj000 {
int myfunc(int x, int y) {return x+*y;} struct myclass{
int operator()(int x, int y){return x+*y;}
}; void test_accumulate()
{
int init = ;
int num[] {, , }; cout<<"default accumulate: " << accumulate(num, num+, init)<< endl; //100 + 10 + 20 + 30 默认累加 cout << "using minus: " << accumulate(num, num+, init, minus<int>())<< endl; //100 - 10 - 20 - 30 将累加改为递减 cout << "using custom function: " << accumulate(num, num+, init, myfunc)<< endl; // 100 + 2*10 + 2*20 + 2*30 //自定义"累加"规则 func cout << "suing custom object: " << accumulate(num, num+, init, myclass())<< endl; // 100 + 3*10 + 3*20 + 3*30//自定义"累加"规则 仿函数
}
} namespace wzj001 {
void myfunc(int i)
{
cout << " - " << i;
} struct myclass{
void operator()(int i)
{
cout << " ^ " << i;
}
}; void test_for_each()
{
vector<int> myVector = {, , };
for_each(myVector.begin(), myVector.end(), myfunc);
cout << endl;
} void test_for_each_classFunc()
{
vector<int> myVector = {, , };
for_each(myVector.begin(), myVector.end(), myclass());
cout << endl;
}
} namespace wzj002 {
struct myclass{
bool operator()(int i)
{
return i >= ? true : false;
}
}; void test_replace()
{
vector<int> myVector = {, , };
replace(myVector.begin(), myVector.end(), ,);
cout << "replace: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
} void test_replace_if()
{
vector<int> myVector = {, , };
replace_if(myVector.begin(), myVector.end(), myclass(), );
cout << "replace_if: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
} void test_replace_copy()
{
vector<int> myVector = {, , };
vector<int> myNewVector;
myNewVector.resize();
replace_copy(myVector.begin(), myVector.end(), myNewVector.begin(), , );
cout << "replace_if_New: ";
for(auto i : myNewVector)
{
cout << i << " ";
}
cout << endl; cout << "replace_if_Old: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
}
} namespace wzj003 {
struct myclass{
bool operator()(int i)
{
return i >= ;
}
}; void test_count()
{
vector<int> myVector = {, , };
cout << "count(): "<< count(myVector.begin(), myVector.end(), ) <<endl;
} void test_count_if()
{
vector<int> myVector = {, , , , , };
cout << "count_if(): " << count_if(myVector.begin(), myVector.end(), myclass()) <<endl;
}
} namespace wzj004 {
struct myclass{
bool operator()(int i)
{
return i >= ;
}
}; void test_find()
{
vector<int> myVector = {, , };
auto tmp = find(myVector.begin(), myVector.end(), );
cout << "find(): "<< distance(myVector.begin(), tmp) <<endl;
} void test_find_if()
{
vector<int> myVector = {, , };
auto tmp = find_if(myVector.begin(), myVector.end(), myclass());
cout << "find_if(): " << distance(myVector.begin(), tmp)<<endl;
}
} namespace wzj005 {
struct myclass{
bool operator()(int i, int y)
{
return i > y;// sort默认降序, 自定义为升序
}
}; void test_sort()
{
vector<int> myVector = {, , , , , , , , };
sort(myVector.begin(), myVector.end());
cout << "sort: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl; } void test_sort_if()
{
vector<int> myVector = {, , , , , , , , };
sort(myVector.begin(), myVector.end(), myclass());
cout << "sort_if: ";
for(auto i : myVector)
{
cout << i << " ";
}
cout << endl;
}
} namespace wzj006 {
struct myclass{
bool operator()(int i, int y)
{
return i > y;
}
}; void test_binary_search()
{
vector<int> myVector = {, , , , , , , , };
cout <<"binary_search: " << (binary_search(myVector.begin(), myVector.end(), ) ? "true" : "false") << endl;
}
} int main(int argc, char *argv[])
{
wzj000::test_accumulate();
wzj001::test_for_each();
wzj001::test_for_each_classFunc();
wzj002::test_replace();
wzj002::test_replace_if();
wzj002::test_replace_copy();
wzj003::test_count();
wzj003::test_count_if();
wzj004::test_find();
wzj004::test_find_if();
wzj005::test_sort();
wzj005::test_sort_if();
wzj006::test_binary_search();
return ;
}

参考侯捷<<STL源码剖析>>

STL标准库-算法-常用算法的更多相关文章

  1. STL标准库-容器-vector

    技术在于交流.沟通,本文为博主原创文章转载请注明出处并保持作品的完整性. 向量容器vector是一个动态数组,内存连续,它是动态分配内存,且每次扩张的原来的二倍. 他的结构如下 一 定义 vector ...

  2. C++STL标准库学习笔记(一)sort

    前言: 近来在学习STL标准库,做一份笔记并整理好,方便自己梳理知识.以后查找,也方便他人学习,两全其美,快哉快哉! 这里我会以中国大学慕课上北京大学郭炜老师的<程序设计与算法(一)C语言程序设 ...

  3. STL标准库-容器-set与multiset

    技术在于交流.沟通,转载请注明出处并保持作品的完整性. set与multiset关联容器 结构如下 set是一种关联容器,key即value,value即key.它是自动排序,排序特点依据key se ...

  4. C++STL标准库学习笔记(二)二分查找

    二.STL中的二分查找算法 1.binary_search 2.lower_bound 3.upper_bound 记得#include<algorithm>! 前言: 在这个笔记中,我把 ...

  5. stl标准库 iterator_traits

    为什么标准库里要有traits? 我们先回忆一下,标准库提供的算法的一些特征: 参数一般包括iterator. 要根据iterator的种类,和iterator包装的元素的类型等信息,来决定使用最优化 ...

  6. C++STL标准库学习笔记(五)set

    前言: 在这个笔记中,我把大多数代码都加了注释,我的一些想法和注解用蓝色字体标记了出来,重点和需要关注的地方用红色字体标记了出来,这一篇后面主要都是我的记录了,为了防止大片蓝色字体出现,后面就不改蓝色 ...

  7. STL标准库-容器-deque

    技术在于交流.沟通,本文为博主原创文章转载请注明出处并保持作品的完整性. deque双向开口可进可出的容器 我们知道连续内存的容器不能随意扩充,因为这样容易扩充别人那去 deque却可以,它创造了内存 ...

  8. STL标准库-容器-set与map

    STL标准库-容器-set与multiset C++的set https://www.cnblogs.com/LearningTheLoad/p/7456024.html STL标准库-容器-map和 ...

  9. C++STL标准库学习笔记(三)multiset

    C++STL标准库学习笔记(三)multiset STL中的平衡二叉树数据结构 前言: 在这个笔记中,我把大多数代码都加了注释,我的一些想法和注解用蓝色字体标记了出来,重点和需要关注的地方用红色字体标 ...

随机推荐

  1. [Shiro] - Shiro之SpringBoot中的使用

    下载了运行项目后,访问路径:http://localhost/shiro/login 这篇应该在进阶后面的. shiro中的重中之重,一定要看. 基于springboot+thymeleaf+shir ...

  2. linux下模拟FTP服务器(笔记)

    要在linux下做一个模仿ftp的小型服务器,后来在百度文库中找到一份算是比较完整的实现,就在原代码一些重要部分上备注自己的理解(可能有误,千万不要轻易相信). 客户端: 客户端要从服务器端中读取数据 ...

  3. 对不队——Alpha冲刺

    第五天  日期:2018/6/20 一. 今日完成任务:专家审稿逻辑的开发 冯晓.马思远:会议网站栏目管理开发,软件功能测试 王爽.彭辉:审稿管理员分稿和稿件查找功能开发,博客撰写 吴琼.郝延婷:更换 ...

  4. 简说Spring事务

    一.事务定义: 事务指逻辑上的一组操作,这组操作要么全部成功,要么全部失败. 二.事务的特性: 1. 原子性 - 指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生. 2. 一致性 ...

  5. 【Golang】 可以自动生成测试用例的库--gotests

    简介 gotests是一个Golang命令行工具,它可以使编写Go的测试代码变得容易.它能基于目标源文件的函数和方法生成数据驱动测试用例,并且在此过程会自动导入任何依赖. 下面是gotests在使用S ...

  6. 【Golang】字符串首字母大小写转化

    写在前面 在自动化过程中,我们用得最多的可能就是字符串的处理,熟悉Python的都知道在Python中要让一个字符串的首字母大写直接用capitalize就可以了,但是同样的事情在Golang中没有这 ...

  7. Java数组的定义和使用

    如果希望保存一组有相同类型的数据,可以使用数组. 数组的定义和内存分配 Java 中定义数组的语法有两种: type arrayName[]; type[] arrayName; type 为Java ...

  8. 10X Genomics vs. PacBio

    10X Genomics已经广泛应用于单细胞测序.组装领域,现在也是火的不行. 10X Genomics原理 通过将来自相同DNA片段(10-100kb)的reads加上相同的barcode,然后在i ...

  9. LeetCode--136--只出现一次的数字

    问题描述: 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 说明: 你的算法应该具有线性时间复杂度. 你可以不使用额外空间来实现吗? 示例 1: ...

  10. mysql5.7执行sql语句出现only_full_group_by错误

    在/etc/my.cnf的[mysqld]组中添加 sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISI ...