List usage
List is a double-ended linked list, so compared with vector, the advantage is that deletion and insertion are faster, but the disadvantage is that random access to data is less efficient.
Many usage of list is similar to that of vector. Here we mainly talk about its usage in different ways.
Define a list object
List <int> lt;
Lt. push_back (88 );
List <int> lt2 (LT );
1. Random Access is not supported
Because Random list access is too slow compared to vector, this function is not provided at all. Therefore, it cannot be used like lt. At (0) or lt [0.
2. Support adding and deleting elements at the header and tail
In vector, push_back and pop_back are only used to add and delete tail elements. In addition to the two functions, list has two more functions.
Lt. push_front (11); // Add an element to the header
Lt. pop_front (); // Delete the element in the header.
3. merge two linked lists
Lt. merge (lt2); // combines LT and lt2 into a linked list, that is, the elements of lt2 are moved to Lt, which is in ascending order by default. lt2 becomes null
4. Delete matching elements
Lt. Remove (11); // delete all elements whose values are 11 in the linked list.
5. Reverse linked list
Lt. Reverse (); // reverse the order of elements in the linked list
6. Order (Ascending by default)
Lt. Sort ();
7. Delete adjacent duplicate elements
Lt. Unique (); // you must first sort it by Lt. Sort (). After sorting, the same element must be adjacent.
Deque usage
Deque also uses dynamic arrays, but the memory management method is a little different from that of vector.
Therefore, the vector has the reserve and Capacity functions, and deque does not.
Deque combines some functions of vector and list.
Data can be accessed randomly (the functions of vector and list are not)
You can add or delete header elements (list has functions that are not available in vector)
Deque <int> de;
De. push_back (88 );
De. push_front (11 );
Int num = de. At (0 );
Int ret = de [0];
De. pop_front ();
De. pop_back ();
Comparison of vector, list, And deque
1. The best performance of vector random access to data.
Therefore, if the data is frequently accessed, but the elements are rarely deleted in other places except the tail, vector is used.
2. The best performance is to randomly add or delete elements to a list.
Therefore, if data is often added and deleted, but less randomly accessed, list is used.
3. deque can randomly access elements, or add or delete elements in the header and tail.
Deque can access data randomly like vector, but its performance is not as good as that of vector. In addition, deque is more efficient than vector in adding and deleting elements in the header. Of course, the performance of deleting and adding elements is not as good as that of list.
Therefore, deque is used when you want to randomly access data and add or delete elements in the header.