20170403STL011_STL_算法和迭代器

来源:互联网 发布:淘宝天天特价入口 编辑:程序博客网 时间:2024/05/22 15:14

STL六大组件:

1:六大组建结合图

2:迭代器作用于容器之上,对容器的操作通过迭代器。
3:algorithm头文件(STL里面的算法头文件):
    1:和之前的命名方式一样,前面带下划线的属于内部使用函数,不带下划线的是对外提供的接口,但是可能带下划线的我们也能访问和使用,但并不建议这样用。
    2:for_each():
template<class InputIterator, class Function>  Function for_each(InputIterator first, InputIterator last, Function fn){  while (first!=last) {    fn (*first);//将给定范围内的元素全部用fn函数处理一遍。    ++first;  }  return fn;      // or, since C++11: return move(fn);}
    调用示例:
#include <iostream>#include <vector>#include <algorithm>template<typename T>void Foo(T t){std::cout << t + 1 << std::endl;}int main(){std::vector<int> vi;vi.push_back(1);vi.push_back(2);vi.push_back(3);vi.push_back(4);vi.push_back(5);vi.push_back(6);vi.push_back(7);vi.push_back(8);vi.push_back(9);vi.push_back(0);for_each(vi.begin(), vi.end(), Foo<int>);//模板函数传递的时候,这个函数本身是不存在的,模板函数本身可以看成一套设备,需要给原料才能出对应的产品//传递的函数是有一定要求的,必须是传递一个参数。/*std::vector<int>::iterator it = vi.begin();//作用于容器之上,通过迭代器来操作for (; it != vi.end();++it){std::cout << *it << std::endl;}*/return 0;}
    3:count_if():
template <class InputIterator, class UnaryPredicate>  typename iterator_traits<InputIterator>::difference_type    count_if (InputIterator first, InputIterator last, UnaryPredicate pred){  typename iterator_traits<InputIterator>::difference_type ret = 0;  while (first!=last) {    if (pred(*first)) ++ret;    ++first;  }  return ret;}
    调用示例:
4:STL从这个图,把相关的一些东西分开了,可以看出STL的GP编程和OOP编程是背道而驰的,他把相关的一些东西分开了,而OOP思想是将所有的抽象成类,连在一起。
5:函数对象:
template<class _Ty = void>struct less: public binary_function<_Ty, _Ty, bool>{// functor for operator<bool operator()(const _Ty& _Left, const _Ty& _Right) const//里面就实现了operator()。{// apply operator< to operandsreturn (_Left < _Right);}};
调用:
std::less<int> i;i(10, 20);
    这种对象就称为函数对象,他就是拿来当函数使用的。也称为仿函数。
6:绑定函数:
template<class _Fn2,class _Ty> inlinebinder2nd<_Fn2> bind2nd(const _Fn2& _Func, const _Ty& _Right){// return a binder2nd functor adaptertypename _Fn2::second_argument_type _Val(_Right);return (_STD binder2nd<_Fn2>(_Func, _Val));}
7:示例:
#include <iostream>#include <vector>#include <algorithm>#include <functional>int main(){std::vector<int> vi;vi.push_back(1);vi.push_back(2);vi.push_back(3);vi.push_back(4);vi.push_back(5);vi.push_back(6);vi.push_back(7);vi.push_back(8);vi.push_back(9);vi.push_back(0);std::less<int> i;i(10, 20);int a = std::count_if(vi.begin(), vi.end(), std::not1(bind2nd(std::less<int>(),3)));//相当于传递了一个函数对象进去。//std::less<>()里面本应该传递两个参数,而count_if只会给他传递一个参数,此时需要用bind2nd或者bind1nd将其中一个参数绑定起来。//此后再调用就只需要传递一个参数了。//std::not1()可以对一个函数执行出来的值取反。return 0;}

8:vector里面的iterator是一个随机访问迭代器。
    注意点:反向迭代器的时候与正向的相同,都是在自己的方向上半闭半开,所以,正向迭代器不能访问end(),反向迭代器不可以访问rend()。否则就可能越界。反响迭代器的操作不符合大多数人的习惯,所以一般用的比较少。
9:list里面的迭代器是双向迭代器(bidirectional_iterator)。
10:SGI STL里面的iterator就是一个指针。没有设计成类的模式。





0 0
原创粉丝点击