STL介绍:

我所理解的stl:

容器: 是一种数据结构,如list,vector,和deques ,以模板类的方法提供。为了访问容器中的数据,可以使用由容器类输出的迭代器;

算法:  是用来操作容器中的数据的模板函数。例如,STL用sort()来对一个vector中的数据进行排序,用find()来搜索一个list中的对象,函数本身与他们操作的数据的结构和类型无关,因此他们可以在从简单数组到高度复杂容器的任何数据结构上使用;

迭代器:  提供了访问容器中对象的方法。例如,可以使用一对迭代器指定list或vector中的一定范围的对象。迭代器就如同一个指针。事实上,C++的指针也是一种迭代器。但是,迭代器也可以是那些定义了operator*()以及其他类似于指针的操作符地方法的类对象;

仿函数:  就是一个类里面重载() 所创建出来的对象,叫做函数对象,或者仿函数

迭代适配器(Adaptor):

空间配制器(allocator): 分配内存的, 偏底层

算法的使用介绍

在stl的算法中分为两大块:一个是全局(泛化)的,一个是容器本身所有的

在使用一个算法时首先看你使用的容器中是否有这个算法,如果有的话,就用容器本身有的

(注意不能使用泛化的,因为泛化的可能不能用这个容器,或者没有容器自带的效率高)

如果没有的话,就使用泛化的

注意这几个例子:图片左边是算法的实现,右边是哪个容器本身有这个算法

count和count_if使用

源码:

  1. /**对谓词为真的序列的元素进行计数。
  2. * @brief Count the elements of a sequence for which a predicate is true.
  3. * @ingroup non_mutating_algorithms
  4. * @param __first An input iterator.
  5. * @param __last An input iterator.
  6. * @param __pred A predicate.
  7. * @return The number of iterators @c i in the range @p [__first,__last)
  8. * for which @p __pred(*i) is true.
  9. */
  10. template<typename _InputIterator, typename _Predicate>
  11. inline typename iterator_traits<_InputIterator>::difference_type
  12. count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
  13. {
  14. return std::__count_if(__first, __last,
  15. __gnu_cxx::__ops::__pred_iter(__pred));
  16. }

使用:

  1. //
  2. // Created by lk on 18-6-4.
  3. //
  4. #include <algorithm>
  5. #include <iostream>
  6. #include <vector>
  7. #include <set>
  8. using namespace std;
  9.  
  10. bool myfun(int i){return i > ;}
  11. struct myClasss{
  12. bool operator()(int i){return i > ;}
  13. }myObjj;
  14.  
  15. int main()
  16. {
  17.  
  18. // 泛化的
  19. vector<int> vec = {,,,,,,,,};
  20. auto num = count(vec.begin(), vec.end(), );
  21. cout << "vec中3的个数为"<< num << endl;
  22.  
  23. auto t = count_if(vec.begin(), vec.end(), myfun);
  24.  
  25. auto t2 = count_if(vec.begin(), vec.end(), myObjj);
  26. cout << t << " " << t2 << endl; // 结果为3 3
  27.  
  28. // 容器本身自带的函数
  29. set<int> s1 = {,,,,};
  30. auto s_num = s1.count();
  31. cout << s_num << endl; //
  32. return ;
  33.  
  34. }

使用方法

find方法:

  1. template<typename _IIter, typename _Tp>
  2. _IIter
  3. find(_IIter, _IIter, const _Tp&);
  4.  
  5. template<typename _FIter1, typename _FIter2>
  6. _FIter1
  7. find_first_of(_FIter1, _FIter1, _FIter2, _FIter2);
  8.  
  9. template<typename _FIter1, typename _FIter2, typename _BinaryPredicate>
  10. _FIter1
  11. find_first_of(_FIter1, _FIter1, _FIter2, _FIter2, _BinaryPredicate);
  12.  
  13. template<typename _IIter, typename _Predicate>
  14. _IIter
  15. find_if(_IIter, _IIter, _Predicate);

find源码

  1. //
  2. // Created by lk on 18-6-4.
  3. //
  4. #include <algorithm>
  5. #include <iostream>
  6. #include <vector>
  7. #include <set>
  8. using namespace std;
  9.  
  10. namespace luck_count{
  11. bool myfun(int i){return i > ;}
  12. struct myClasss{
  13. bool operator()(int i){return i > ;}
  14. }myObjj;
  15.  
  16. int test_count()
  17. {
  18.  
  19. // 泛化的
  20. vector<int> vec = {,,,,,,,,};
  21. auto num = count(vec.begin(), vec.end(), );
  22. cout << "vec中3的个数为"<< num << endl;
  23.  
  24. auto t = count_if(vec.begin(), vec.end(), myfun);
  25.  
  26. auto t2 = count_if(vec.begin(), vec.end(), myObjj);
  27. cout << t << " " << t2 << endl; // 结果为3 3
  28.  
  29. // 容器本身自带的函数
  30. set<int> s1 = {,,,,};
  31. auto s_num = s1.count();
  32. cout << s_num << endl; //
  33. return ;
  34.  
  35. }
  36. }
  37. namespace luck_find{
  38. bool myFun(int i) {return i > ;}
  39. struct MyClass{
  40. bool operator()(int i) {return i > ;}
  41. }myObj;
  42. void test()
  43. {
  44. vector<int> vec = {,,,,,,,,};
  45.  
  46. auto it = find(vec.begin(), vec.begin()+, );
  47. cout << "it是6的迭代器地址" << endl;
  48. auto it2 = find_if(vec.begin(), vec.end(), myFun);
  49. cout << "use custom functional" << endl;
  50. cout << "it2是大于2的迭代器地址" << endl;
  51. auto it3 = find_if(vec.begin(), vec.end(), myObj);
  52. cout << "use custom object" << endl;
  53. cout << "it3是大于2的迭代器地址" << endl;
  54.  
  55. }
  56. }
  57. int main()
  58. {
  59. luck_count::test_count();
  60. luck_find:: test();
  61. return ;
  62. }

使用方法find和count

sort用法

包含仿函数

  1. /**使用比较的谓词来排序序列的元素。
  2. * @brief Sort the elements of a sequence using a predicate for comparison.
  3. * @ingroup sorting_algorithms
  4. * @param __first An iterator.
  5. * @param __last Another iterator.
  6. * @param __comp A comparison functor.
  7. * @return Nothing.
  8. *
  9. * Sorts the elements in the range @p [__first,__last) in ascending order,
  10. * such that @p __comp(*(i+1),*i) is false for every iterator @e i in the
  11. * range @p [__first,__last-1).
  12. *
  13. * The relative ordering of equivalent elements is not preserved, use
  14. * @p stable_sort() if this is needed.
  15. */
  16. template<typename _RandomAccessIterator, typename _Compare>
  17. inline void
  18. sort(_RandomAccessIterator __first, _RandomAccessIterator __last,
  19. _Compare __comp)
  20. {
  21. // concept requirements
  22. __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
  23. _RandomAccessIterator>)
  24. __glibcxx_function_requires(_BinaryPredicateConcept<_Compare,
  25. typename iterator_traits<_RandomAccessIterator>::value_type,
  26. typename iterator_traits<_RandomAccessIterator>::value_type>)
  27. __glibcxx_requires_valid_range(__first, __last);
  28. __glibcxx_requires_irreflexive_pred(__first, __last, __comp);
  29.  
  30. std::__sort(__first, __last, __gnu_cxx::__ops::__iter_comp_iter(__comp));
  31. }

sort源码

  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <set>
  5. #include <functional>
  6.  
  7. namespace luck_sort{
  8. void print(vector<int> &vec)
  9. {
  10. for (auto item : vec)
  11. cout << item << " ";
  12. cout << endl;
  13. }
  14. bool myfun(int i, int j){return i > j;}
  15. struct myclass{
  16. bool operator ()(int i, int j){return i < j;}
  17. }myObj;
  18. // 仿函数对象省略了
  19. void test()
  20. {
  21. vector<int> vec = {,,,,,,,-};
  22. sort(vec.begin(), vec.end());
  23. cout << "use default 谓词"<<endl;
  24. print(vec);
  25.  
  26. cout << "use default functional"<<endl;
  27. sort(vec.begin(), vec.end(), less<int>()); // greater<int>() 从大到小排序
  28. print(vec);
  29.  
  30. sort(vec.begin(),vec.end(), myfun);
  31. cout << "use custom fun" << endl;
  32. print(vec);
  33.  
  34. sort(vec.begin(),vec.end(), myObj);
  35. cout << "use custom object" << endl;
  36. print(vec);
  37. cout << endl;
  38. }
  39. }
  40. int main()
  41. {
  42. // luck_count::test_count();
  43. // cout << endl;
  44. // luck_find:: test();
  45. // cout << endl;
  46. luck_sort:: test();
  47. return ;
  48. }

sort用法

仿函数

仿函数:就是一个类里面重载() 所创建出来的对象,叫做函数对象,或者仿函数

有些功能的的代码,会在不同的成员函数中用到,想复用这些代码。

1)公共的函数,可以,这是一个解决方法,不过函数用到的一些变量,就可能成为公共的全局变量,再说为了复用这么一片代码,就要单立出一个函数,也不是很好维护。

2)仿函数,写一个简单类,除了那些维护一个类的成员函数外,就只是实现一个operator(),在类实例化时,就将要用的,非参数的元素传入类中

c和c++中的仿函数

1)c语言使用函数指针和回掉函数来实现仿函数,例如排序函数中使用仿函数:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //int sort_function( const void *a, const void *b);
  4. int sort_function( const void *a, const void *b)
  5. {
  6. return *(int*)a-*(int*)b;
  7. }
  8.  
  9. int main()
  10. {
  11.  
  12. int list[] = { , , , , };
  13. qsort((void *)list, , sizeof(list[]), sort_function);//起始地址,个数,元素大小,回调函数
  14.  
  15. for (auto x = ; x < ; x++)
  16. printf("%d\n", list[x]);
  17.  
  18. return ;
  19. }

2)在C++里,我们通过在一个类中重载括号运算符的方法使用一个函数对象而不是一个普通函数。

  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. using namespace std;
  5. template<typename T>
  6. class display
  7. {
  8. public:
  9. void operator()(const T &x)
  10. {
  11. cout<<x<<" ";
  12. }
  13. };
  14.  
  15. int main()
  16. {
  17. int ia[]={,,,,};
  18. for_each(ia,ia+,display<int>()); //循环遍历数组
  19.  
  20. return ;
  21. }

仿函数在STL中的定义

要使用STL内建的仿函数,必须包含<functional>头文件。而头文件中包含的仿函数分类包括

1)算术类仿函数

加:plus<T>

减:minus<T>

乘:multiplies<T>

除:divides<T>

模取:modulus<T>

否定:negate<T>

  1. #include <iostream>
  2. #include <numeric>
  3. #include <vector>
  4. #include <functional>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. int ia[]={,,,,};
  10. vector<int> iv(ia,ia+);
  11. cout<<accumulate(iv.begin(),iv.end(),,multiplies<int>())<<endl; //加法
  12.  
  13. cout<<multiplies<int>()(,)<<endl; //乘法
  14.  
  15. modulus<int> modulusObj; //取模运算
  16. cout<<modulusObj(,)<<endl; // 3
  17. return ;
  18. }

示例

2)关系运算类仿函数

等于:equal_to<T>

不等于:not_equal_to<T>

大于:greater<T>

大于等于:greater_equal<T>

小于:less<T>

小于等于:less_equal<T>

从大到小排序:

  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. template <class T>
  8. class display
  9. {
  10. public:
  11. void operator()(const T &x)
  12. {
  13. cout<<x<<" ";
  14. }
  15. };
  16.  
  17. int main()
  18. {
  19. int ia[]={,,,,};
  20. vector<int> iv(ia,ia+);
  21. sort(iv.begin(),iv.end(),greater<int>());
  22. for_each(iv.begin(),iv.end(),display<int>());
  23. return ;
  24. }

3)逻辑运算仿函数

逻辑与:logical_and<T>

逻辑或:logical_or<T>

逻辑否:logical_no<T>

bind和适配器

如果想要统计和比20大的数,用自带的仿函数不行,又不像自己写,或者自己写,要写很多,所以用适配器,绑定参数,这里是绑定less中的第二个参数, 原本less中是x>y 现在就变成x>20

这里的调用过程: 在vec的序列中,统计不满足后面的条件的数的个数

Less<int>()是一个临时的仿函数对象(class A ==> A a()) ,不是调用函数 

但是现在bind2nd被改成bind  bind的功能更加强大,绑定很多个参数

这里主要讲bind的使用

  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <set>
  5. #include <functional>
  6.  
  7. namespace luck_bind{
  8. // bind(函数对象,仿函数对象, 对象要的参数_1,_2,...)
  9.  
  10. template<typename T>
  11. void print(vector<T> &vec)
  12. {
  13. for (auto item : vec)
  14. {
  15. cout << item << " ";
  16. }
  17. cout << endl;
  18. }
  19.  
  20. // a function: (also works with function object: std::divides<double> my_divide;)
  21. double my_divide (double x, double y) {return x/y;}
  22.  
  23. struct MyPair {
  24. double a,b;
  25. double multiply() {return a*b;}
  26. };
  27.  
  28. void test() {
  29. // 这句话必须写, 还有functional头文件
  30. using namespace std::placeholders; // adds visibility of _1, _2, _3,...
  31.  
  32. // binding functions:
  33. auto fn_five = std::bind (my_divide,,); // returns 10/2
  34. std::cout << fn_five() << '\n'; //
  35.  
  36. auto fn_half = std::bind (my_divide,_1,); // returns x/2
  37. std::cout << fn_half() << '\n'; //
  38.  
  39. auto fn_invert = std::bind (my_divide,_2,_1); // returns y/x
  40. std::cout << fn_invert(,) << '\n'; // 0.2
  41.  
  42. auto fn_rounding = std::bind<int> (my_divide,_1,_2); // returns int(x/y)
  43. std::cout << fn_rounding(,) << '\n'; //
  44.  
  45. MyPair ten_two {,};
  46.  
  47. // binding members:
  48. auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply()
  49. std::cout << bound_member_fn(ten_two) << '\n'; //
  50.  
  51. auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a
  52. std::cout << bound_member_data() << '\n'; //
  53.  
  54. vector<int> vec = {,,,,,-,};
  55. cout << "bind and bind2nd different"<<endl;
  56. cout << count_if(vec.begin(), vec.end(), not1(bind2nd(less<int>(), ))) << endl;
  57.  
  58. cout << "use bind of count_if"<<endl;
  59. auto fn = bind(less<int>(), _1, );
  60. cout << count_if(vec.begin(), vec.end(), fn); // 小于4的有几个 4个
  61.  
  62. cout << "\nbind sort" << endl;
  63. sort(vec.begin(), vec.end(), less<int>());
  64.  
  65. print<int>(vec); // 模板函数
  66. sort(vec.begin(), vec.end(), bind(less<int>(), _2, _1));
  67. print<int>(vec);
  68. }
  69. }
  70.  
  71. int main()
  72. {
  73. // luck_count::test_count();
  74. // cout << endl;
  75. // luck_find:: test();
  76. // cout << endl;
  77. // luck_sort:: test();
  78. luck_bind::test();
  79.  
  80. return ;
  81. }

测试_必看

STL杂记的更多相关文章

  1. 面试基础知识集合(python、计算机网络、操作系统、数据结构、数据库等杂记)

    python python _.__.__xx__之间的差别 python中range.xrange和randrange的区别 python中 =.copy.deepcopy的差别 python 继承 ...

  2. 2016.6.19——C++杂记

    C++杂记 补充的小知识点: 1.while(n--)和while(--n)区别: while(n--)即使不满足也执行一次循环后跳出. while(--n)不满足直接跳出循环,不执行语句. 用cou ...

  3. 详细解说 STL 排序(Sort)

    0 前言: STL,为什么你必须掌握 对于程序员来说,数据结构是必修的一门课.从查找到排序,从链表到二叉树,几乎所有的算法和原理都需要理解,理解不了也要死记硬背下来.幸运的是这些理论都已经比较成熟,算 ...

  4. STL标准模板库(简介)

    标准模板库(STL,Standard Template Library)是C++标准库的重要组成部分,包含了诸多在计算机科学领域里所常见的基本数据结构和基本算法,为广大C++程序员提供了一个可扩展的应 ...

  5. STL的std::find和std::find_if

    std::find是用来查找容器元素算法,但是它只能查找容器元素为基本数据类型,如果想要查找类类型,应该使用find_if. 小例子: #include "stdafx.h" #i ...

  6. STL: unordered_map 自定义键值使用

    使用Windows下 RECT 类型做unordered_map 键值 1. Hash 函数 计算自定义类型的hash值. struct hash_RECT { size_t operator()(c ...

  7. C++ STL简述

    前言 最近要找工作,免不得要有一番笔试,今年好像突然就都流行在线笔试了,真是搞的我一塌糊涂.有的公司呢,不支持Python,Java我也不会,C有些数据结构又有些复杂,所以是时候把STL再看一遍了-不 ...

  8. [Erlang 0118] Erlang 杂记 V

       我在知乎回答问题不多,这个问题: "对你职业生涯帮助最大的习惯是什么?它是如何帮助你的?",我还是主动回答了一下.    做笔记 一开始笔记软件做的不好的时候就发邮件给自己, ...

  9. codevs 1285 二叉查找树STL基本用法

    C++STL库的set就是一个二叉查找树,并且支持结构体. 在写结构体式的二叉查找树时,需要在结构体里面定义操作符 < ,因为需要比较. set经常会用到迭代器,这里说明一下迭代器:可以类似的把 ...

随机推荐

  1. NLP之分词

    不同分词工具原理解析 对各种分词工具的介绍,具体参考: http://www.cnblogs.com/en-heng/p/6234006.html 1) jieba 具体参考: https://blo ...

  2. machine_math

    1.导数与函数的凹凸性关系: 从下往上看,如果函数是凸出来的就是凸函数,如果是凹的就是凹函数. 函数的凹凸性是二阶函数来判断的. 如果二阶函数大于零,那么就是凸函数,否则就是凹函数. 2.一阶导数为零 ...

  3. 黑苹果MacOS安装记录

    https://blog.daliansky.net/macOS-Catalina-10.15-19A583-Release-version-with-Clover-5093-original-ima ...

  4. oracle--ORA-38760

    01,ORA-38760: This database instance failed to turn on flashback 02,问题处理思路 第一步:查看日志文件 查看这次启动的时候alter ...

  5. vue组件component没效果

    如果实在不知道问题所在,你就看看你的component的命名是不是驼峰命名

  6. 19条常用的MySQL优化方法(转)

    本文我们来谈谈项目中常用的MySQL优化方法,共19条,具体如下:1.EXPLAIN命令做MySQL优化,我们要善用EXPLAIN查看SQL执行计划.下面来个简单的示例,标注(1.2.3.4.5)我们 ...

  7. Extra:Variable Types

    文章著作权归作者所有.转载请联系作者,并在文中注明出处,给出原文链接. 本系列原更新于作者的github博客,这里给出链接. 在我们使用Cg或者HLSL进行shader编写的过程中,常常涉及到一些变量 ...

  8. c++小学期大作业攻略(一)环境配置

    UPDATE at 2019/07/20 20:21 更新了Qt连接mysql的方法,但是是自己仿照连VS的方法摸索出来的,简单测试了一下能work但是不保证后期不会出问题.如果你在尝试过程中出现了任 ...

  9. gcc/g++ -O 优化选项说明

    查查gcc手册就知道了,每个编译选项都控制着不同的优化选项 下面从网络上copy过来的,真要用到这些还是推荐查阅手册 -O设置一共有五种:-O0.-O1.-O2.-O3和-Os. 除了-O0以外,每一 ...

  10. 利用SQL计算两个地理坐标(经纬度)之间的地表距离

    两个地理坐标(经纬度)地表距离计算公式: 公式解释如下: Long1,Lat1表示A点经纬度,Long2,Lat2表示B点经纬度: a=Lat1–Lat2 为两点纬度之差,b=Long1-Long2为 ...