设为首页 加入收藏

TOP

从STL中学习泛型编程
2014-10-21 19:30:03 来源: 作者: 【 】 浏览:60
Tags:STL 学习 编程

  最近在看数据结构方面的书籍,遇到了泛型编程方面的问题,以前遇到的泛型编程问题不多,大多数也已经遗忘,于是打算重新捡起来。下面一段关于泛型编程的定义摘抄于百度百科,应该能概括什么事泛型编程。


  泛型编程让你编写完全一般化并可重复使用的算法,其效率与针对某特定数据类型而设计的算法相同。泛型编程的代表作品STL是一种高效、泛型、可交互操作的软件组件。所谓泛型(Genericity),是指具有在多种数据类型上皆可操作的含意,与模板有些相似。STL巨大,而且可以扩充,它包含很多计算机基本算法和数据结构,而且将算法与数据结构完全分离,其中算法是泛型的,不与任何特定数据结构或对象类型系在一起。STL以迭代器 (Iterators)和容器(Containers)为基础,是一种泛型算法(Generic Algorithms)库,容器的存在使这些算法有东西可以操作。STL包含各种泛型算法(algorithms)、泛型指针(iterators)、泛型容器(containers)以及函数对象(function objects)。STL并非只是一些有用组件的集合,它是描述软件组件抽象需求条件的一个正规而有条理的架构。


  上面的概括只是从理论上解释了什么是泛型,可是看过后还是不知道怎么使用泛型,于是乎笔者找到了STL中定义的头文件,下面就一步一步解开泛型的秘密。


  由于原版的STL中很多类的套嵌,不便于解释,所以简化了STL,以下以vector容器为例:


  文件名:vector.h


  1: template //模板定义了Object类型,在使用的时候可以以任何类型代替此类型


  2: class vector


  3: {


  4: public:


  5: explicit vector( int initSize = 0 ) : theSize( initSize ), theCapacity( initSize + SPARE_CAPACITY )//重点注意构造函数的定义,构造函数支持两种方式初始化vector容器,这下知道怎么用vector了吧


  6: { objects = new Object[ theCapacity ]; }


  7: vector( const vector & rhs ) : objects( NULL )


  8: { operator=( rhs ); }


  9: ~vector( )


  10: { delete [ ] objects; }


  11:


  12: bool empty( ) const


  13: { return size( ) == 0; }


  14: int size( ) const


  15: { return theSize; }


  16: int capacity( ) const


  17: { return theCapacity; }


  18:


  19: Object & operator[]( int index )


  20: {


  21: #ifndef NO_CHECK


  22: if( index < 0 || index >= size( ) )


  23: throw ArrayIndexOutOfBoundsException( index, size( ) );


  24: #endif


  25: return objects[ index ];


  26: }


  27:


  28: const Object & operator[]( int index ) const


  29: {


  30: #ifndef NO_CHECK


  31: if( index < 0 || index >= size( ) )


  32: throw ArrayIndexOutOfBoundsException( index, size( ) );


  33: #endif


  34: return objects[ index ];


  35: }


  36:


  37: const vector & operator = ( const vector & rhs );


  38: void resize( int newSize );


  39: void reserve( int newCapacity );


  40:


  41: // Stacky stuff


  42: void push_back( const Object & x );


  43: void pop_back( );


  44: const Object & back ( ) const;


  45:


  46: // Iterator stuff: not bounds checked


  47: typedef Object * iterator;


  48: typedef const Object * const_iterator;


  49:


  50: iterator begin( )


  51: { return &objects[ 0 ]; }


  52: const_iterator begin( ) const


  53: { return &objects[ 0 ]; }


  54: iterator end( )


  55: { return &objects[ size( ) ]; }


  56: const_iterator end( ) const


  57: { return &objects[ size( ) ]; }


  58:


  59: enum { SPARE_CAPACITY = 16 };


  60:


  61: private:


  62: int theSize;


  63: int theCapacity;


  64: Object * objects;


  65: };


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇从sockaddr中取得Ip地址和端口号 下一篇位域具体存放数值测试

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: