Primary knowledge STL Analysis list part source code

Source: Internet
Author: User

1. STL

the first bit of the design of library functions is commonality, which provides the possibility of templates, and all the algorithms and containers in the standard Template Library are implemented through templates .

STL (Standard Template Library) is one of the most characteristic and practical parts of C + +.

The entire STL architecture model is as follows:

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/85/3E/wKiom1eeACaT6uI5AAAjHS5z_gI075.png-wh_500x0-wm_3 -wmp_4-s_3282288414.png "title=" Qq20160731214223.png "alt=" Wkiom1eeacat6ui5aaajhs5z_gi075.png-wh_50 "/>

2, List (two-way loop linked list)

Call the #include<list> of the STL system, and use the system's two-way circular linked list structure to handle:

#include <iostream> #include <list>//Call system list, bidirectional circular linked list structure using namespace Std;int main (void) {LIST<INT&G T    MyList  for (int i = 1; i <=; i++) {mylist.push_back (i); interface, added at the end} list<int>::iterator it = Mylist.begin ();   Iterator, while (it! = Mylist.end ()) {cout<<*it<< "--";//print internal digital ++it; Move backward One} cout<< "NULL" <<ENDL;}

3, the list part of the source Code implementation analysis

The list model is as follows:

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M01/85/3F/wKioL1eeDInRFRNMAAAPcaneWs8163.png-wh_500x0-wm_3 -wmp_4-s_2771346436.png "title=" Qq20160731223410.png "alt=" Wkiol1eedinrfrnmaaapcanews8163.png-wh_50 "/>

Read its source code and analyze some of the features:

#ifndef  _list_h   //conditional macro compilation to avoid duplicate definitions #define _list_h#include<assert.h>    //asserts that the header file introduced by the #include<malloc.h>   //application space introduced by the header file template<class _ty> // The space adapter Class list{    //list class public:    struct _node; is not involved here first     typedef struct _node* _nodeptr;  //pointer type to node      struct _node{   //_node This is the node type          _nodeptr _prev;    //precursor node         _nodeptr  _next;    //successor node         _Ty       _value;   //Template Data Types     };     struct _acc{  //defines _ACC this type         typedef struct  _node*& _nodepref;  //reference to pointer to node type         typedef _Ty&            _vref;      //references to this data type          static _nodepref _next (_nodeptr _p)//static method,  The return value is a reference to the node pointer &nbsp, and the parameter is a pointer to the node         {return  ((_nodepref) (*_p). _ Next);} : *_p Gets this node, () The precedence of the type cast is not. High, so at this point first take _next, in the work of coercion type conversion, returns a reference to the node pointer.         static _nodepref _prev (_Nodeptr _P)          {return  ((_nodepref) (*_p). _prev);}         static _vref _value (_Nodeptr _P)          {return  ((_vref) (*_p). _value);}      };p ublic:  //The following types are the types _a this class, _a this class is defined in the space adapter      typedef typename _a::value_type           value_type;     typedef typename _a::p ointer_type          Pointer_type;    typedef typename _a::const_pointer_type   const_ pointer_type;    typedef typename _a::reference_type        reference_type;    typedef typename _a::const_reference_type  const_reference_type;    typedef typename _A::size_type             size_type;  //This type is actually size_tprivate:     _nodeptr  _head;   //pointer to head node     size_type  _size;   //number of nodes}; #endif

The above code is mainly struct _ACC the understanding of this class is very important!!!

Here's the constructor and destructor.

Public:    explicit list (): _head (_buynode ()), _size (0)   //explicit display Call this constructor, Give the head a point, just start 0     {}    ~list ()     {      //free space and Space Configurator, at this stage do not care.         erase (Begin (),  end ()),   //call start, End Function free space;         _freenode (_head);        //release head;         _Head = 0, _Size = 0;    //are empty;    }     .... protected:    _nodeptr _buynode. ..... ..... ......------------------------ nodeptr _narg=0, _nodeptr _parg=0)   //  The return value is the node pointer type, the parameters are node pointer type, the transmission should be the successor and precursor pointers, the default is 0;     {        _Nodeptr _S =  (_ NODEPTR) malloc (sizeof (_node));//apply for a sectionPoint space, give the address to _s;                 ASSERT (_s != null);   //the space applied for exists         _acc::_ Next (_s)  = _narg!=0 ? _narg : _s; //assigns a value to the newly generated node _next          _acc::_prev (_s)  = _parg!=0 ? _parg : _s; //to the newly generated node. _prev assignment         return _s; //Returns the address of this new build node      }//This _buynode function means: When the first node is created, its own node to itself, forming a two-way circular linked list, the other case is inserted between two nodes!!! ........................................................

Next write iterator:

The public:    class iterator{   //iterator is also a class, which is the inner class of the list;     public:        iterator ()          {}        iterator (_nodeptr _p): _Ptr (_P)          {}    public:       Operator overloading for   iterator& operator++ () {  // ++it, front + +              _ptr=_ptr->_next; //because it is a linked list structure, the internal implementation of the Iterator + +, is the overload of the + + ; make its pointer move to the next node;            return *this;    //returns a reference to this node.         }        iterator  operator++ (int)// it++        {              _it it (_ptr);   //first save the original node              _ptr = _ptr->_next; //move to the next node              return it;  //back to the original;         }        iterator operator--(int);  / /similar         iterator& operator--();         reference_type operator* () const //heavy duty on *          {return _ptr->_value;}    //returns the _value value of this node         pointer_type operator- > () const //Heavy-duty         //{return &_ptr->_ Value;}    self-implemented,-> priority is higher than &amp, so the _value address is returned &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; {return  (&**this);} In the   //system, this is the address of the iterator, the *this is the iterator object, and another * is called (the overload of the *), at which point the address of the _value is returned.     public:        bool operator!= (const  iterator &it) Comparison of const  //iterator objects         {return  _ptr!=it._ptr;}   //is a pointer to a node;     public:        _ Nodeptr _mynode () const //Gets the address of the current node;         {return _ptr ;}     protected:        _Nodeptr _Ptr;  The data member of the   //iterator is a pointer to the node.     };    typedef iterator _It;  //_It  Is the iterator type Public:    iterator begin () {Return iterator (_acc::_next (_Head));} The   //begin () function gets the successor of the header (the address of the first valid node)     iterator begin () Const;    iterator end () {return iterator (_head);} The   //end () function Gets the head node (that is, the successor address of the last node);p ublic:          The                //in front of me is very clear, The following are all calls;     void push_back (const _ty &x)        {insert (End (), x);}     void push_front (const _ty &x)     {insert (Begin ( ), x);} Public:    iterator insert (Iterator _p, const _ty &_x=_ty ())     {        _nodeptr _s = _p._ Mynode ();   //get node address         _acc::_prev (_S)  = _ Buynode (_s, _acc::_prev (_s))   //The following three lines call the preceding function _buynode () implements the Insert function;         _s =&nbSp;_acc::_prev (_s);         _acc::_next (_Acc::_Prev (_S))  = _S ;         ++_size;  //number plus 1         return iterator (_s);     }    void insert ( ITERATOR&NBSP;_P,&NBSP;SIZE_TYPE&NBSP;_M,&NBSP;CONST&NBSP;_TY&NBSP;&AMP;_X)  //Inserts the number _M, the following several calls the preceding function;     {        for (;  0<_m; --_m)              insert (_p,_x);    }     void insert (iterator _p, const _ty *_f, const _ty *_ L) insertion     {        for of  //interval (; _F!=_L;  ++_f)             insert (_P, *_F);     } &nbInsertion of the Sp;  void insert (iterator _p, _it _f, _it _l)   //iterator     {        for (;  _F!=_L; ++_F)              insert (_p, *_f);     }    /*    void push_back (const _Ty &x)    //trailing add last     {        _nodeptr _s =  _buynode (_head, _acc::_prev (_head))  //Implement Insert Function         _ Acc::_value (_s)  = x;        _acc::_next (_Acc::_Prev (_Head))  = _s;        _acc::_prev (_Head)  = _S;         _size++;  //last Add 1    }     iterator erase (iterator _p)//  Delete space     {        _nodeptr  _S =  (_p++). _mynode ();         _acc::_next (_acc::_prev ( _s)  = _acc::_next (_s);         _acc::_prev (_Acc::_Next (_S))  = _acc::_prev (_s);          --_size;  // Reduce the number of 1         return _P;    }     iterator erase (iterator _f, iterator _l)  //call function, delete interval      {        while (_f != _l)              erase (_f++);         return  _f;    }    void clear ()  //Clear all space      {erase (Begin (),  end());} #endif

4. Summary:

(1), the essence of the iterator has an understanding, is an internal class, it will be an object, the internal data member is a pointer to the node;

(2), the overload of the iterator to, returns the address of the node's internal data, not the address of the node;

(3), iterators do not have the same implementation for each data structure (Stack, queue, List ...)

(4), Space Configurator: For all data structures, there is only one copy,

Role: Application, release space, structure, destructor object;



Primary knowledge STL Analysis list part source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.