1. 认识header、版本、重要资源

头文件命名形式:

  • C++标准库header files 不带(.h)
  • 新型的C头文件不带.h
  • 原先的C头文件(带有.h)的,仍旧可以使用(但是最好还是使用最新的形式)
  • 所有的新式headers都在名字域“std”中
  • 旧式的头文件不被包含在“std”中

2.STL体系结构基础介绍

STL的六大部件:

  • 容器
  • 分配器
  • 算法
  • 迭代器
  • 适配器
  • 仿函数(Functors)

1 24

include // 与容器同名

include

include

include

using namespace std;

int main() { int ia[6] = {27, 210, 12, 47, 109, 83}; vector<int, allocator> vi(ia, ia+6);// 分配器用于分配内存(一般默认)

/*
count_if: algorithm;
not1: function adapter(negator);
bind2nd: 绑定第二参数,function adapter(binder)
less: function object
*/

cout << count_if(vi.begin(), vi.end(),
			not1(bind2nd(less<int>(), 40)));  // 大于等于40

return 0; }

标准库中的容器都是前开后闭的。但是容器的end()方法指向的是容器最后的元素的下一个元素,所以直接将这个指针解引用出来,得到的是一个未知的东西。

1 10

Container c; .... Container::iterator ite = c.begin(); for(; ite != c.end(); ++ite) ...

// C++11 for(auto& elem : c){ … }

3~6. 容器分类与各种测试

标准库中的集合和map一般用红黑树实现。

代码习惯:测试程序放在名字域中,对应的库放在对应的名字域中,对应的定义变量需要的时候再写,为了注明,定义变量不会进行缩进。

vector: 对于空间扩充是呈现两倍增长的。这个增长是通过找到一个新的内存,然后将原先的元素全部复制到这个新的空间中,所以这个增长的过程实际上是比较缓慢的。

deque : 分段,但是逻辑上是连续的。没有自己的sort

关联式容器查找都非常快

multiset:内部是红黑树实现的,可以包含重复元素

1

multisetc;

multimap:不可以使用[]作为插入

1 3

multimap<long, string>c; c.insert(pair<long, string>(i, buf)); // 访问需要使用first & second

unordered_multiset:散列表实现的(哈希表)

set: 不会出现重复的元素

map: 底层实现是红黑树, 可以使用[]添加元素,key不重复,value是有重复的

7. 分配器测试

分配器用于内存分配

1 4

int* p; __gnu_cxx::malloc_allocator alloc; p = alloc.allocate(1); alloc.deallocate(p, 1); // 不建议使用,需要记住申请的内存的大小(用于空间释放)

8.源代码分布

9. OOP & 泛化编程

泛化编程是将数据和方法分开来了。容器与算法(方法)之间通过迭代器相互关联。

为什么list不能使用::sort()?
因为::sort()中使用的迭代器指针需要是能够随机访问的(能前能后),但是在list中,这种性质不满足。

特化
模板在特定类型的时候使用特定的方法(更优的)

1 35

// 泛化 template struct __type_traits{ .... };

//特化 template<> struct __type_traits{ .... };

//特化 template<> struct __type_traits{ .... };

// 偏特化,如果传入的是一个指针(范围上的偏特化) template struct __type_traits<type*>{ .... };

// 泛化 template <class T, class Alloc = alloc> class vector{ …. };

// 偏特化:仅将其中一个模板参数进行特化(数量上的局部) template class vector<bool, Alloc> { .... };

11.分配器

malloc申请内存的时候是有额外的开销的(其中包括了申请的空间的大小)。当申请的空间比较小的时候,这种开销占比比较大
在VC6的allocator中知识以::operator new 和 ::operator delete 完成allocate() 和 deallocate() 没有特殊设计。

1 34

#ifndef _FARQ #define _FARQ #define _PDFT ptrdiff_t #define _SIZT size_t

endif

define _POINTER_X(T, A) T_FARQ*

define _REFFERENCE_X(T, A) T_FARQ&

template inline _Ty _FARQ* _Allocate(_PDFT _N, _Ty _FARQ*) { $$if(_N < 0) _N = 0;$$ return ((_Ty _FARQ*) operator new((_SIZT)_N*sizeof(_Ty))); }

template class allocator{ public: typedef _SIZT size_type; typedef _PDFT difference_type; typedef _Ty _FARQ * pointer; typedef _Ty value_type; pointer allocate(size_type _N, const void*) // 第二个是任意参数 { return (_Allocate((difference_type) _N, (pointer)0)); }

void deallocate(void _FARQ *_P, size_type)
{ operator delete(_P); } };

// 分配512 ints int* p = allocator().allocate(512, (int*0)); allocator().deallocate(p, 512); // 用临时变量调用类方法

这种方式可能会导致太大的额外开销,所以,一些改进的方法是一次申请固定倍数大小的空间,这样可以减少malloc的使用(与vector中的空间拓展思想类似)

13、14. list源代码

i++ 和 ++i
因为符号一样,所以给后置版本加一个int形参作为区分,这个形参是0,但是在函数体中是用不到的,只是为了区分前置后置。

1 2

self operator++(int) { … } // i++ self operator++() { … } // ++i (可以认为i作为参数已经传入了)

另外整数不能连续进行两次后连加,可以前加(++++i √,i++++ × )

为了满足容器前闭后开的性质,在list链表中会有一个空白的头节点,这个就是end指针指向的节点,其内部实际上是一个环形双向链表。

15. Iterator 必须提供的5种相关类别

  • iterator_category
  • value_type
  • pointer
  • reference
  • difference_type

1 9

template struct iterator_traits { typedef typename I::iterator_category; typedef typename I::value_type; typedef typename I::difference_type; typedef typename I::pointer; typedef typename I::reference; };

萃取机(iterator_traits): 用于分离class iterator 和 non-class iterator。这是用过偏特化实现的

1 34

template struct iterator_traits{ typedef typename I::value_type value_type; };

// 两种偏特化 template struct iterator_traits<T*>{ typedef T value_type; };

template struct iterator_traits<const T*>{ typedef T value_type; // 不能用const T,因为这样声明的变量无法赋值 };

// 获取I的value_type template<typename I, …> void algorithmn(…){ typename iterator_traits::value_type v1; }

// 一个实例

template struct iterator_traits<T*> { typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; };

16.vector深度探索

在进行扩充的时候,需要重新申请空间,并且原先的空间将会被销毁,这使得这个过程中需要调用大量的构造函数和析构函数。

如果是连续空间,那么这个容器的迭代器就可以单纯地使用指针来表现。

17. array、forward_list 深度探索

在特化array的时候,需要指明大小,这是因为array的大小是固定的,它没有构造器和析构器。

1 8

array<int, 10> myArray;

// 定义数组 int a[100]; // √ //int[100] a; // ×

typedef int T[100]; T c; // √

18,19. deque、queue和stack深度探索

deque:这个容器的地址是由几个内存段产生的,用一个向量存储每一个内存段的首地址。对于迭代器,是由一个类组成,其中包含当前内存块的边界,当前指针指向的元素,以及当前内存块在地址向量中的位置

1 35

// 这里会找到离边界最近的方向移动元素 iterator insert(iterator position, const value_type& x){     if(position.cur == start.cur){ // 是否是在开头         push_front(x);         return start;     }     else if(position.cur == finish.cur){// 是否是在尾部         push_back(x);         iterator tmp = finish;         –tmp;         return tmp;     }     else{         return insert_aux(position, x);     } }

template <class T, class Alloc, size_t BufSize> typename deque<T, Alloc, BufSize>::iterator deque<T, Alloc, BufSize>::insert_aux(iterator pos, const value_type){ \(difference_type index = pos - start;\) \(value_type x_copy = x;\) if(index < size()/2){ // 检查是否小于中点 push_front(front()); //复制第一个元素 … copy(front2, pos1, front1); // 全部往前移动 } else{ push_back(back()); …. copy_backward(pos, back2, back1); } \(*pos = x_copy;\) return pos; }

模拟连续空间,累加,[],向前移动元素

在stack和queue中,默认一个deque。 这两者可选择list或deque作为底层结构。二者不可用set或map作为底层结构。转调用的时候,一些函数不满容器特性。 这二者不允许遍历,也不提供iterator,这种操作会干扰容器的特性(FIFO 或 FILO)

二者不同的是,queue 不可选择vector作为底层结构,stack可以。

1 9

template<class T, class Sequence=deque> class queue{ .... protected: Sequence c;// 底层容器 ... };

stack<string, llist>c;

RB-tree

关联式容器。 RB-tree:平衡二叉搜索树。有利于search和insert。rb_tree 的迭代器不应该用于修改元素,但是未被禁止这种操作,因为它为set和map服务,而map允许data被修改,只有key不可以被修改,此时,红黑树是根据map的key进行排序的。 红黑树提供两种insertion操作:insert_unique(), insert_equal前者key是要求独一无二的,后者可以有重复

1 15

template<class Key, class Value, class KeyOfValue, class Compare, class Alloc=alloc> class rb_tree{ protected: typedef __rb_tree_node rb_tree_node; ... public: typedef rb_tree_node* link_type; ... protected: // 大小为9,但是为了内存对齐,这里实际上占用的内存为12 size_type node_count; // 节点个数 link_type header; Compare key_compare; // key的大小比较准则,是一个函数对象.理论上是0,但是实现为1 ... }

21.set & multiset

  • 一个元素不可重复,一个可以重复。
  • 无法使用二者的iterator改变元素值,这些容器中的key有其固定的排列规则,这种iterator底层是RB tree的const iterator
  • 元素特性是key就是value, value就是key
  • 在实现中,set都是在调用rb tree中的操作,所以可以说set是一个容器的适配器

22.map & multimap

  • 与之前不同的是,这里的value被分为key和data
  • 其他的性质与22中提到的类似
  • multimap 不可使用[], map可以,如果找到,则返回值,如果没有就将键值插入到map中。

1 7

// 调用逻辑 map<int, string>my_map; map<int, string, less, alloc>my_map;

// selectlst: 获取键值,第一个元素 template <int, pair<const int, string>, selectlst<pair<const int, string», less, alloc> class rb_tree;

23,24、hash table

  • 直接使用原始数字作为键值需要大量的空间,所以通常采用原始数据与一个素数的余数作为键值,这个素数可以被成为“篮子”(扩充大小实际上时固定的,根据不同的版本存在不同)
  • 当元素个数大于篮子的数时,需要rehashing,重新规划篮子的大小(选下一个素数作为篮子大小,这样所有的元素都要重新计算)。

26.unodered容器概念

C++之后,将原先的hash_set、hash_miltiset、hash_map、hash_miltimap中的hash编程unordered

27.算法形式

算法的所需的一切信息都由迭代器取得

28. 迭代器的分类

随机访问迭代器、双向迭代器、单向迭代器 random_access_iterator, bidirectional_iterator, forward_iterator.

1 6

// 特殊的迭代器 display_category(istream_iterator()); // input_iterator display_category(ostream_iterator(cout, "")); // output_iterator

#include typeid(itr).name(); // 查看变量类型

29. 迭代器分类对算法的影响

如果是随机访问迭代器,那么迭代器可以直接到达指定的位置,如果是input_iterator,迭代器只能一个个加到指定的位置,这种功能可以通过偏特化实现(特化迭代器的类型)

对于output iterator是write-only,无法像forward iterator那样可以read, 所以不可以使用*运算符进行读取

30.算法源码剖析

accumulate

1 33

include

include

include

namespace jj34 {     using namespace std;     int myfunc(int x, int y){ return x + 2 * y }         struct myclass{

        int operator()(int x, int y){ return x + 3 * y; }

    }myobj;         void test_accumlate()     {         int init = 100;         int nums[] = {10, 20, 30};                 // default         cout « accumulate(nums, nums + 3, init); // 160

        // using functional’s minus         cout « accumulate(nums, nums + 3, init, minus());  //40                 // Using self-defined function         cout << accumulate(nums, nums + 3, init, myobj); //        /* $$init = binary_op(init, *first) // binary_op 就是传入的函数,可以传入函数或者仿函数(重载括号运算符)$$        */     } }

for_each

replace, replace_if, replace_copy 1.替换元素,2。在给定条件下替换 3.不删除被替换元素,将其复制到其他位置

count, count_if

find, find_if find:循序查找

sort: 传入迭代器范围

1 2

sort(vec.begin(), vec.begin() + 3); // 默认从小到大, i < j vec.rbegin() = vec.end(); // 一个反向的迭代器

binary_search

仿函数和函数对象

binder2nd

1 2

// 这里的less() 不是在调用,这是一个对象 count_if(v.begin(), v.end(), not(bind2nd(less(), 40)));

仿函数可被适配的条件

1 20

template<class Arg, class Result> struct unary_function{ typedef Arg argument_type; typedef Result result_type; };

template <class Arg1, class Arg2, class Result> struct binary_function{ typedef Arg1 first_argument_type; typedef Arg2 second_argument_type; typedef Result result_type; };

// 每一个可适配的函数都会继承上面的结构体,因为需要向Function adapter提供上面结构体定义的信息 template struct less : public binary_function<T, T, bool>{ bool operator()(const T& x, const T& y)const {return x < y;} };

新型适配器bind上述适配器已被弃用。

34. not1

35.bind (C++11)

可以绑定:

  • functions
  • function object
  • member function (_1需要是地址)
  • data member(_1需要是地址)

1 29

double my_divide(double x, double y) { return x/y; }

struct MyPair{ double a, b; double multiply(){return a*b;} };

using namespace std::placeholder; // adds visibility of _1, _2 ….

\(auto fn_five = bind(my_divide, 10, 2);\) cout « fn_five() ; // 5

\(auto fn_five = bind(my_divide, _1, 2); // _1 占位符\) cout « fn_five(10) ; // 5

\(auto fn_five = bind(my_divide, _2, _1); // _2 第二个占位符\) cout « fn_five(10, 2) ; // 5

// 指定return type 为int \(auto fn_five = bind<int>(my_divide, _2, _1); // _2 第二个占位符\) cout « fn_five(10, 2) ; // 5

MyPair ten_two{10, 2}; \(auto bound_memfn = bind(&MyPair::multiply, _1);\) cout « vound_memfn(ten_two); // 20

// 本质上就是将函数中的一个参数绑定一个固定的值 // ps: cbegin:表示constant