您的位置:首页 > 编程语言 > C语言/C++

C++STL&GP学习后记——初识STL

2017-06-20 11:13 309 查看
 前几天有幸上了侯捷老师的GP(Generic Programming)-STL的选修课,现在把这几天学的东西整理下,一是为了后天的考试小小复习下,另外也当作新的帐号的第一篇博客。(如有什么讲的不对的地方,请斧正) 

       什么是STL呢?STL就是Standard Template Library,标准模版库。然而,C++的STL,虽然是一套程式库,却不只是一般印象中的程式库,而是一个有着划时代意义,背后拥有先进技术与深厚理论的产品。——《STL源码剖析》_侯捷 

       首先,让我们看看STL的六大组件: 

       1. 容器(containers):各种数据结构,如vector,list,deque,set,map等。 

       2. 算法(algorithms):各种算法如sort,serach,copy,erase等。 

       3. 迭代器(iterators):扮演容器预算法之间的胶合剂,是所谓的‘泛型指针’。 

       4. 仿函数(functors):行为类似函数,其实是一个类,只不过重载了operator (),使之具有类似函数的行为。 

       5. 适配器(adapters):一种用来修饰容器,仿函数或迭代器界面的东西。 

       6. 分配器(allocators):负责空间配置与管理。 

       六组件的关系如下图:

             


        

       Container透过allocator取得存储空间,algorithm透过iterator存取container内容,functor可以协助algorithm完成不通的策略变化,adapter可以修改或套接functor。

       下面是一个使用了六大组件的实例程序,虽然很短,可是麻雀虽小五脏俱全:

        

[html] view
plain copy

 print?

#include --------------------------------------------1  

[html] view
plain copy

 print?

#include -----------------------------------------2  

[html] view
plain copy

 print?

#include ----------------------------------------3  

[html] view
plain copy

 print?

#include ------------------------------------------4  

[html] view
plain copy

 print?

  

[html] view
plain copy

 print?

using namespace std;-----------------------------------------5  

[html] view
plain copy

 print?

  

[html] view
plain copy

 print?

int main()---------------------------------------------------6  

[html] view
plain copy

 print?

{   

[html] view
plain copy

 print?

int ia[6] = {27,210,12,47,109,83};----------------------7   

[html] view
plain copy

 print?

vector> vi (ia,ia+6);-------------8   

[html] view
plain copy

 print?

cout<< count_if(vi.begin(), vi.end(),<span style="color:#FF0000;">not1(bind2nd(less<int>(),40))</span>);-9   

[html] view
plain copy

 print?

return 0;----------------------------------------------------------10  

[html] view
plain copy

 print?

}   

        <int,allocator其中1-3是含有六大组建的头文件,8的allocator是一个分配器,vector<int,allocator>是一个容器,9的vi.begin(),vi.end()都是迭代器,count_if是算法,less是仿函数或者称函数对象,bind2nd和not1是适配器,在这里用来适配函数对象,所以不妨称为函数适配器。
         我们大致来看一下这个程序是做什么的: 首先,声明了一个含有六个整数的数组,然后声明了一个vector(集合),尖括号中的int表示这个vector放的是整型,allocator是一个分配器(其实可以省略,省略的话系统会使用默认的分配器),这两个是是vector模版中的泛型具体化,然后把数组ia的头地址和尾地址(具体来说是数组最后一个元素的后面一个地址)作为vector的参数,这样就得到了一个含有六个整数的容器对象。 

<int,allocator<int,allocator         接下来是count_if算法,第一,二个参数分别是包含容器开始和末尾节点的迭代器,红色部分整个是一个仿函数,它是由less<int>(也是一个仿函数),经过两个适配器:bind2nd,not1改造而成。less<int>()接受两个参数arg1,arg2,返回arg1<arg2,bind2nd把<arg2,bind2nd是把less第二个参数绑定为40,not1则是把结果取反,所以count_if做的事就是遍历容器中每个元素i(把红色整体看作p),进行p(i)调用,返回结果为真的个数,所以上例应返回结果4。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: