Summary of list containers in STL

Source: Internet
Author: User

1. About list containers

List is a sequential container. The functions completed by the list container are actually very similar to the two-way linked list in the data structure. The data elements in the list are a linear table in the logic sense through the linked list pointer string, that is, list also has the main advantages of a linked list, that is, it is fast to insert or delete elements at any position in the linked list. The implementation of list is like this: each node in list has three fields: the pre-element pointer field, the data field, and the subsequent element pointer field. The pointer field of the precursor element stores the first address of the precursor element, the data field is the data of the current node, and the pointer field of the subsequent element stores the first address of the subsequent element. In fact, the list and circular linked list are similar, that is, the header node's precursor element pointer field stores the first address of the tail element in the linked list, the pointer field of the successor element of the End Node of list stores the first address of the header node. In this way, list actually forms a bidirectional loop chain.Because list element nodes do not need to be in a continuous memory, they obviously do not support fast random access in list. Therefore, for the iterator, you can only use the "++" or "--" operation to move the iterator to the successor/precursor node element. Rather than performing + N or-N operations on the iterator, this is different from that of vector.

 

It is necessary to compare the three commonly used sequence types:

Vector:Like the built-in array, vector has a continuous memory space, which can be easily accessed immediately, that is, the [] Operator. However, because its memory space is continuous, therefore, inserting and deleting in the middle will cause a copy of the memory block. In addition, when many elements are inserted, the reserved memory space may not be enough, you need to apply for a large enough memory and copy the original data to the new memory space. These affect the efficiency of vector, but the most used is the vector container. We recommend that you use vector in most cases. Vector usage analysis can refer to my own another article: http://www.cnblogs.com/BeyondAnyTime/archive/2012/08/08/2627666.html

List:List is a two-way linked list in the data structure (according to SGI STLSource code). Therefore, its memory space is discontinuous and data access is performed through pointers. This feature makes its access to data very inefficient, therefore, it does not provide an overload of the [] operator. However, due to the characteristics of the linked list, it supports deletion and insertion anywhere with good efficiency.

Deque:Deque is a double-ended queue. Its implementation is not clear, but it has the following two features: it supports [] operators, that is, instant access, the efficiency is almost the same as that of vector. It supports operations at both ends: push_back, push_front, pop_back, pop_front, and so on, and the operation at both ends is similar to that of list.

 

Therefore, in actual use, how to select one of the three containers depends on your needs.Principles:
1. If you need efficient instant access without worrying about the efficiency of insertion and deletion, use the Vector
2. If you need to insert and delete a large number of objects without having to access them immediately, you should use list
3. If you need immediate access and care about data insertion and deletion at both ends, deque should be used.

 

2. List common functions

Constructors in 2.1list:

List () declares an empty list;

List (n) declares a list with n elements. Each element is constructed by its default constructor T ().

List (n, Val) declares a list of n elements. Each element is obtained by its copy constructor T (VAL ).

List (n, Val) declares the same list as above

List (first, last) declares a list. The initial values of the elements come from the elements in the sequence specified by the interval.

2.2 begin () and end ():Call the member function begin () of the list container to obtain an iterator pointing to the starting position of the container. You can call the end () function of the List container to obtain the next position at the end of the list container, which is equivalent: the n + 1 position a [n] In int A [n] does not actually exist and cannot be accessed. It is often used as a condition for judging the end of the loop.

2.3 push_back () and push_front ():Use the List member functions push_back and push_front to insert an element to the list. Push_back () is inserted from the end of the list, while push_front () is inserted from the header of the list.

2.4 empty ():Use empty () to determine whether the list is empty.

2.5Resize ():If you call resize (n) to change the length of the list to accommodate only n elements, the excess elements will be deleted. If you need to expand, the default constructor T () will be called () add the element to the end of the list. If you call resize (n, Val), the extension element calls the constructor T (VAL) function to construct the element, and the rest are the same.

2.6 clear ():Clear all elements in the list.

2.7 Front () and back ():Through Front ()You can get the Header element in the list container, and get the last element of the List container through back. However, when the elements in the list are empty, what will happen when calling Front () and back? In fact, data cannot be normally read, but this does not report an error.ProgramI think it is best to call the empty () function to determine whether the list is empty before use.

2.8 pop_back and pop_front ():PassDelete the last element and use pop_front () to delete the first element. The sequence must not be empty. If the list is empty, calling pop_back () and pop_front () will cause the program to collapse.

2.9 assign ():Similar to the operations in vector, there are two cases. The first one is: l1.assign (n, Val) converts the elements in L1 into n t (VAL ). The second case is: l1.assign (l2.begin (), l2.end () assigns the value from l2.begin () to l2.end () in L2 to L1.

2.10 swap ():Exchange two linked lists (two reloads), one isL1.swap (L2); The other isSwap (L1, L2) may all complete the exchange of linked lists.

2.11 reverse ():Use reverse () to reverse the list.

2.12 Merge ():Merge two linked lists and make them in ascending order by default (can also be changed), L1. Merge (L2, greater <int> (); after the call, L2 becomes null. L1 contains elements in the original L1 and L2, sorted in ascending order. In fact, the default value is ascending. Greater <int> () can be omitted. In addition, greater <int> () can be changed or not arranged in ascending order.

Check out the following program:

View code

 1 # Include <iostream> 2 # Include <list> 3   4   Using   Namespace  STD;  5  6   Int  Main ()  7   {  8 List < Int > L1;  9 List < Int > L2 ( 2 , 0  );  10 List < Int >: Iterator ITER;  11 L1.push _ back ( 1  );  12 L1.push _ back ( 2  );  13 L2.push _ back ( 3  );  14 L1.merge (L2, greater < Int > ()); //  Sort in ascending order after merging. The default value is ascending.  15      For (Iter = l1.begin (); iter! = L1.end (); ITER ++ )  16   {  17 Cout <* ITER < "   "  ;  18   }  19 Cout <Endl < Endl;  20       If  (L2.empty ()) 21   {  22 Cout < "  L2 becomes null !!  "  ;  23   }  24 Cout <Endl < Endl;  25       Return   0  ;  26 }

Running result:

2.13 insert ():Insert one or more elements (three overloading) at the specified position ):

L1.insert (l1.begin (), 100); insert 100 at the beginning of L1.

L1.insert (l1.begin (), 2,200); insert 2 100 at the beginning of L1.

L1.insert (l1.begin (), l2.begin (), l2.end (); inserts the elements of L2 from start to end at the starting position of L1.

2.14 erase ():Delete an element or an element of a region (two reloads)

L1.erase (l1.begin (); Delete the first element of L1.

L1.erase (l1.begin (), l1.end (); deletes the L1 elements from begin () to end.

 

Let's take a look at some of the lessons learned.

 

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.