STL: Sequence Container vector summary

Source: Internet
Author: User

We are all familiar with the array, but in C + + there is a "new friend" in addition to the array, which is the vector. In fact, Vector is similar to the data arrangement and operation mode of array in essence. The only difference between the two is space flexibility.

In both C and C + +, the space of an array cannot be changed once the application is completed, and if more space is needed to store the data, it is necessary to reapply a new array and copy the original values before releasing the original array, all of which need to be done by the user himself. Unlike vectors, where the space allocation is more flexible, when his memory is not enough to store, its internal mechanism will be self-expanding capacity, which is more flexible and convenient for programmers to use.
Vector structure diagram:

Let's take a look at how the vector is shown in STL.

Template<classTclassAlloc = alloc>//defined as template class, configure space by default using Alloc. class Vector{ Public://rename type to be more convenient and easy to use.    typedefT Value_type;typedefvalue_type* pointer;typedefvalue_type& reference;typedefValue_type* iterator;typedefsize_t Size_type;typedefptrdiff_t Difference_type;protected://Fill and initialize    voidFill_initialize (size_type N,ConstT &value) {start = Allocate_and_fill (N,value);//construct and populatefinish = Start+n;//Adjust finish to point to the next space in the last elementEnd_of_storage = finish;//Let end_of_storage point to the tail of the space that is currently available}//Construct space and fill the initial valueIterator Allocate_and_fill (size_type N,ConstT &x) {iterator result = Data_allocator::allocate (n);//configure n spaces, at which point the allocate () is essentially the Simple_alloc () function in the space-time Configurator usedUninitialized_fill_n (RESULT,N,X);//use X to fill N of space        returnResult//Return to the first address of the vector} Public://construct a vector with an initial value    Vector(): Start (0), Finish (0), End_of_storage (0){}//Constructs a vector that can hold n elements, and the initial values are populated with default values    Vector(Size_type N)    {fill_initialize (n,t ()); }    ~Vector()    {}Private:typedefSimple_alloc<value_type, alloc> Data_allocator;//Simple_alloc<value_type, alloc> RenameIterator start;//point to the currently used space headerIterator finish;//point to the end of the currently used spaceIterator end_of_storage;//point to the end of the space currently available}

Here are some simple interface functions:

Iteratorbegin(){returnStart;}//Get the head of the vectorConst_iteratorbegin() const {returnStart;}//Get vector head common methodIteratorEnd(){returnFinish;}//Get the tail of the vectorConst_iteratorEnd() const {returnFinish;}//The usual method of getting the tail of a vectorSize_type size () {returnSize_type (End() -begin());}//gain effective length of vectorSize_type capacity () {returnSize_type (End_of_storage-begin());}//Get the total capacity of the vectorSize_type max_size () const{returnSize_type (-1)/sizeof (T);}//bool Empty () {returnSize = =0;}//EmptyReference Front () {return*begin();}//Get the value of the headConst_reference Front () const {return*begin;}//The usual method of getting the head valueReference back () {return*End();}//Get the trailing valueConst_reference back () const {return*(End() -1);}//The usual method of getting the trailing valueReference operator[] (size_type N) {return*(begin() + n);}//overload [], so that it and the array can access the value of the element by subscriptConst_reference operator[] (size_type N) const{return*(begin() + n);}constant method for//overload []

To delete a location element:

    erase(iterator position)    {     //把范围在[position+1,finish)内的元素拷贝到以position为起始位置的空间内        if(position + 1 != end()){            copy(position + 1, finish, position);        }        //改变目前finish指向        -- finish;        //销毁finish位置的元素(多于出来的)        destroy(finish);        position;    }

Local deletion function of vector erase ()

//删除first到last之间的元素iterator earse(iterator first, iterator last){    //将last到finish之间的元素拷贝到以first处开始位置,并将finish存放位置返回    copy(last, finish, first);    //销毁i到finish位置元素    destroy(i, finish);    //调整目前finish的指向    finish = finish - (last - first);    return first;}

The main functions of copy () in Erase () are:

copylastfirst){    forlastfirst0--n, ++first, ++last){        *first = *last;     }    returnfirst

Expansion:
Vector's space seems to be "self-growing" relative to array, but the vector's "growth" is an illusion. It's still going to be a lot more space to pursue. Vector Expansion Trilogy: (1), apply for enough, greater space. (2), copy the original data into the new space. (3), release the original space.

    resize(size_type new_size, const T& x)    {        if(new_size < size()){            erase(begin() + new_size, end());        }else{            insert(end, new_size - size(), x);          }    }    resize(size_type new_size){resize(new_size, T());}

Insert functions and DELETE functions:
Vector re-insertion and deletion of the general is the end and end of the delete, in the source of the vector is also only provided by the tail Plug and tail delete. Because this is a matter of efficiency, head-deletion and head-insertion efficiency are very low, because it involves moving all the elements forward, so that its time complexity is related to the number of elements. Therefore, considering the efficiency problem, the source code does not provide pre-insertion and pre-deleted interface functions.

Tail Delete:

pop_back()  {      --finish;         //调整finish指向     destroy(finish);  //销毁finish}

Tail Plug:

push_back(const T &x){    if(finish != end_of_storage){    //如果还有备用空间        construct(finish, x);        //在finish处用x构造一个节点        ++finish;                    //更改目前finish的指向    }else{        insert_aux(end(), x);       //没有备用空间则调动insert_aux()    } }

The implementation of the Insert_aux () function:
In Insert_aux (), instead of connecting a new space behind the original space when expanding the spare space, reconfigure a larger space that is twice times the size of the original. Because we cannot guarantee that there is space behind the original space to be configured. But the reason to choose to reconfigure the size of the original size is twice times because, in order to eliminate the hassle of expanding space.

void Insert_aux (iterator position,ConstT &x) {if(Finish! = end_of_storage) {//There is a spare space,Construct (Finish, * (Finish-1));//Constructs an element at the start of the standby space. Use the last element of the vector as the initial value. ++finish;//Change the point of the current finishT x_copy = x; Copy_backward (position, Finish-2, Finish-1);//Diagram below*position = x_copy;///Then put the x_copy value in the position you want to insert}Else{//No spare space        ConstSize_type old_size = size ();//Record the original size        ConstSize_typeLen= old_size! =0?2* Old_size:1;//If the original size is 0, the 1 element size is configured, and if the original size is not 0, the original size twice times the space is configured. Iterator New_start = Data_allocator::allocate (Len);//Configure a space of size LenIterator new_finish = New_start; New_finish = uninitalized_copy (start, Position, New_start);//Copy elements in the [start, position] range to start at New_startConstruct (new_finish, x);//Use x to construct an element at position++new_finish;//Adjust the direction of New_finishNew_finish = uninitalized_copy (position, Finish, new_finish);//Copy the elements in the [position, finish] range to a position starting with new_finish. and point the new new_finish back to the        //destructors and release of the original vectorDestroy (Begin (), end ()); Deallocate ();//Adjustment iterator, pointing to the new vectorstart = New_start;        finish = New_finish; End_of_storage = New_start +Len; }}

--copy_back () Implementation method when there is a spare space:

When there is no spare space:

Insert () function: Inserts n elements at the specified position with an initial value of x:

voidInsert (iterator position, Size_type N,Constt& x) {if(n! =0){//When n! =0 do the following, or return directly        if(Size_type (End_of_storage-finish) >= N) {//Spare space >= the number of new elements. T x_copy = x;ConstSize_type elems_after = finish-position;//Gets the number of elements after the insertion pointIterator old_finish = finish;if(Elems_after > N) {//If the number of elements after the insertion point is greater than the number of new elementsUninitialized_copy (Finish-n, Finish, finish);//Move elements in the [Finish-n, finish] range to start with finish so that n space is empty before finishFinish + = n;//Adjust finish current pointCopy_backward (position, old_finish, finish);//Position,old_finish The element in the range (finish-old_finish) "N"Finish + = Elems_after; Fill (position, old_finish, x_copy);//Insert new value in position}Else{///insertion point element number less than new value addedUninitialized_fill_n (Finish, N-elems_after, x_copy);//In the finish the fill in (elems_after-n) elements, the initial value is X. The number of elements after the insertion point equals the number of new value addedFinish + = N-elems_after;//Adjust the point of finish to correctUninitialized_copy (position, old_finish, finish);//Position,old_finish The element in the range (finish-old_finish) "N"Finish + = Elems_after;//Adjust the point of finishFill (position, old_finish, x_copy);//Insert new value in position}            }Else{//Spare space is less than the new element            //Reconfigure the new vector size            ConstSize_type old_size = size ();ConstSize_type len = old_size +Max(Old_size, N);            Iterator New_start = data_allocator::allocate (len);            Iterator new_finish = New_start; New_finish = uninitialized_copy (start, Position, New_start);//Copy the element before the insertion point value of the original vector to the new spaceNew_finish = Uninitialized_fill_n (New_finish, n, x);//Fill in new vector with added elements (fill in where current new_finish point)New_finish = uninitialized_copy (position, Finish, new_finish);//Copy the element after the insertion point in the original vextor to the new space}    }}

Insert n elements in the specified program implementation process:


The above is the source of the vector operation interface. Here the code may be relatively fragmented, and only a simple interface program, if you need source code can be downloaded at the following URL:

Sgi_stl Source: http://www.sgi.com/tech/stl/download.html

STL: Sequence Container vector summary

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.