STL container details, stl container details

Source: Internet
Author: User
Tags bitset

STL container details, stl container details

STL containers can be divided into the following categories:
I. Sequence containers, including vector, list, deque, string.

2. Associated containers: set, multiset, map, mulmap, hash_set, hash_map, hash_multiset, and hash_multimap

3. Miscellaneous: stack, queue, valarray, and bitset

 

The container class shares some public interfaces. Three sequence container types defined by the standard library: vector, list, And deque (abbreviation of double-ended queue, Which is pronounced as "deck"). Their differences are only in the way of accessing elements, and the cost of adding or deleting elements. Ordered container adapters include stack, queue, and priority_queue. The container only defines a small number of operations, most of which are provided by the algorithm library. If the two containers provide the same operation, their interfaces (function names and number of parameters) should be the same.

Standard containers Description
Ordered container
Vector Quickly insert and delete elements from the backend to directly access any elements
Deque You can quickly insert and delete elements from the front or back to directly access any element.
List Double-stranded tables, fast insertion and deletion from anywhere
Associated container
Set Quick search, repeated values not allowed
Multiset Quick search, allowing repeated values
Map One-to-multiple ing, fast search based on keywords, repeated values are not allowed
Multimap One-to-multiple ing, fast search based on keywords, allowing repeated values
Container Adapter
Stack Back-in-first-out
Queue First-in-first-out
Priority_queue The highest priority element is always the first column

Container Type

Vector Container, supporting fast Random Access (continuous storage)
List Linked List, supporting fast insertion/deletion
Deque Dual-end queue, supporting Random Access (continuous storage), fast insertion and deletion at both ends
Stack Stack
Queue Queue
Priority_queue Priority queue
The following table lists the operations provided by the iterator for all container types:
* Iter Returns the reference of the element to which the type iter points.
Iter-> mem Dereference iter and obtain the specified member.
++ Iter Add 1 to iter to point to the next element in the container
Iter ++  
-- Iter Subtract 1 from iter to point to the previous element in the container.
Iter --  
Iter1 = iter2 When two iterators direct to the same element in the same container or
Iter1! = Iter2 When the next position of a container exceeds the end, the two iterators are equal.
The iterator of the vector and deque containers provides additional operations: the arithmetic operations of the iterator and other relational operations, as shown in the following table:
Iter + n Adding (subtract) an integer to the iterator generates an iterator pointing to the nth element in the container;
Iter-n The new iterator must point to the elements in the container or the next position beyond the container end.
Iter1 + = iter2 Compound operation: First add (subtract) and then assign a value
Iter1-= iter2  
Iter1-iter2 Applicable only to vector and deque
>,>=, <,<= Compare the positional relationship of the iterator; applicable only to vector and deque
Relational operators are only applicable to vector and deque containers, because only these two containers provide fast and random access to their elements. They ensure that the specified container elements can be accessed directly and effectively based on the element location. Both containers support random access through element positions, so their iterators can effectively implement arithmetic and relational operations. Iterator range: [first, last) is a left closed range, indicating that the range starts from first to last, but does not include last. NOTE: If first is not equal to last, the auto-increment operation on first must be able to reach last; otherwise, that is, the last is before first, and undefined behavior will occur. The range of the iterator uses left closed: Because this can uniformly represent empty sets, no special processing is required. In addition, when using the iterator, pay special attention to the possible failure problems of the iterator. Access Element
Back () Returns the reference of the last element of the container. If the container is empty, this operation is not defined
Front () Returns the reference of the first element of the container. If the container is empty, this operation is not defined
C [n]

Returns the reference of an element whose subscript is n. If n <0 or n> = size (), this operation is not defined.
(Note: Only applicable to vector and deque containers)

At [n] Returns the reference of an element whose subscript is n. If the subscript is invalid, an exception out_of_range is thrown.
(Note: Only applicable to vector and deque containers)
Delete Element
Erase (p) Delete the element pointed to by iterator p. Returns an iterator pointing to the elements behind the deleted element. If p points to the last element in the container, the returned iterator points to the next position of the container beyond the end. If p itself is the iterator pointing to the next position beyond the end, the function is not defined.
Erase (B, e) Delete all elements in [B, e. Returns an iterator pointing to the elements behind the deleted element segment. If e itself is an iterator pointing to the next position beyond the end, the returned iterator also points to the next position beyond the end.
Clear () Delete all elements in the container and return void
Pop_back () Delete the last element in the container and return void. If the container is empty, this operation is not defined.
Pop_front () Delete the first element in the container and return void. If c is an empty container, this operation is not defined.
(Note: Only applicable to list and deque containers)
Assignment and swap
C1 = c2 Delete all elements of container c1 and copy the elements of c2 to container c1. C1 and c2 must be of the same type.
C1.swap (c2) Exchange Content: after this function is called, c1 stores the original c2 elements, and c2 stores the original c1 elements. C1 and c2 must be of the same type. The execution speed of this function is usually faster than copying c2 elements to c1.
C. assign (B, e)

Re-set the elements of c: Copy all the elements in the range marked by iterator B and e to c. B and e must not be the iterator pointing to elements in c.

C. assign (n, t) Reset container c to store n elements whose values are t.
Note: The assign operation first deletes all elements in the container, and then inserts the new elements specified by the parameter into the container. The swap operation does not delete or insert any elements, and ensures exchange within the constant time. The iterator does not expire because no elements are moved in the container. Note that these iterators point to elements in another container. Container selection:The vector and deque containers provide quick access to elements, but the cost is that inserting or deleting elements anywhere in the container is more costly than inserting and deleting elements at the end of the container, to ensure its continuous storage, you need to move elements. The list type can be quickly inserted and deleted at any location, because continuous Storage is not required, however, the cost is that the random access overhead of elements is large. Features: 1) Like a vector container, insert or erase elements in the deque container are less efficient. 2) unlike a vector container, the deque container provides efficient insert and erase operations in its header, just like at the end; 3) Unlike the list container, which is the same as the vector container, the deque container supports random access to all elements. 4) Deleting an element at the beginning or end of the deque container will only invalidate the iterator pointing to the deleted element. Insert and delete operations at any other location of the deque container will invalidate all iterators pointing to the container element. Container comparison:

Vector (continuous space storage, you can use the [] Operator) to quickly access random elements, quickly Insert elements at the end, but insert Between the ages of the sequence, it takes a long time to delete an element, and if the space allocated at the beginning is not enough, there will be a performance overhead for re-allocating a larger space and then copying it.
Deque) quick access to random elements, fast insertion of elements at the beginning and end, random insertion, slow deletion of elements, and faster Space reallocation than vector, the original elements do not need to be copied. To sort a deque, copy the deque to the vector first, and then copy it back to deque.
List (each element is connected with a linked list) does not access a random element as fast as a vector, and random inserted elements are faster than a vector. Therefore, space is allocated to each element. Therefore, there is no sufficient space and the allocation is re-allocated.


Set: the internal elements are unique and stored in a balance tree structure. Therefore, the elements are sorted during traversal and the search speed is relatively high.
Map: the combination of one-to-one mappings, and keys cannot be repeated.

Stack: the adapter must be used with other containers. The default internal container in stl is deque. First, only one exit is available, and traversal is not allowed.
Queue: it is a restricted deque. It is easier to use a list for internal containers. First-in-first-out, traversal not allowed.
Vector <bool> and bitset <>. The length can be changed dynamically.
Priority_queue: The inserted element has a priority order, and the top element has the highest priority.
Valarray is specialized in numerical calculation and adds special mathematical functions.

Some container selection rules: 1) If the program requires Random Access to elements, the vector or deque container should be used;2) If the program must insert or delete elements in the middle of the container, the list container should be used;3) if the program is not in the middle of the container, but inserts or deletes elements in the header or tail of the container, deque container should be used; 4) if you only need to insert elements in the middle of the container when reading the input, and then randomly access the elements, you can read the elements into a list container during the input, and then sort the containers, then copy the sorted list container to the vector container. 5) if the program requires both random access and insertion or deletion of elements in the middle of the container, the impact of which operation should be weighed, to decide whether to select the list container or the vector or deque container. Note: If you choose to use a vector or deque container, you can consider using only the operations they share with the list container, such as using an iterator instead of a subscript to avoid random element access, in this way, you can easily rewrite the program to use the list container when necessary. Container adapter is a common concept in the standard library, including container adapter, iterator adapter, and function adapter. Essentially, an adapter is a mechanism that makes the behavior of one thing look similar to the behavior of another thing. The container adapter allows an existing container type to work in a different abstract type, but only interface conversion occurs. The standard library provides three sequence container adapters: queue, priority_queue, and stack. All adapters define two constructors: the default constructor is used to create an empty object, and the constructor with a container parameter takes the copy of the parameter container as its basic value. The default stack and queue are implemented based on the deque container, while the priority_queue is implemented on the vector container. When creating an adapter, You can overwrite the associated basic container type by specifying an ordered container as the second type parameter of the adapter. For example: stack <int, vector <int> int_stack; // at this time, the int-stack is based on the vector implementation for the given adapter, the associated container must meet certain constraints. The basic container associated with the stack adapter can be any sort of ordered container type, because these container types provide push_back, pop_back, and back operations; the queue adapter requires that the associated basic container must provide the pop_front operation, so it cannot be created on the vector container; The priority_queue adapter requires random access, so it cannot be created on the list container. Two adapters of the same type can be = ,! =, <,>, <=,> = Relational operations, as long as their basic element types support the = and <operations. This is consistent with the container size comparison principle. This is consistent with the container size comparison principle. Stack
S. empty () True if the stack is set to this person; otherwise, false is returned.
S. size () Returns the number of elements in the stack.
S. pop () Deletes the top element of the stack but does not return its value.
S. top () Returns the value of the top element of the stack, but does not delete the element.
S. push (item) Push new elements into Stack items
The standard library queues of queues and Priority Queues use the first-in-first-out (FIFO) storage and retrieval policies. elements entering the queue are placed at the end, and the next retrieved element is taken from the queue header. Priority_queue uses the element type <operator by default to determine the priority relationship between them. You can also define your own priority relationship. In a priority queue, a new element is placed before an element with a lower priority.
Q. empty () If the queue is empty, true is returned; otherwise, false is returned.
Q. size () Returns the number of elements in the queue.
Q. pop () Deletes the first element of a team, but does not return its value.
Q. front () Returns the value of the first element, but does not delete the element.
(Note: This operation only applies to queues)
Q. back () Returns the value of the end element, but does not delete the element.
(Note: This operation only applies to queues)
Q. top ()

Returns an element with the highest priority, but does not delete the element.
(Note: This operation only applies to priority queues. MSDN also provides this operation for queue)

Q. push (item) For queue, a new element is pushed at the end of the team;
For priority_queue, insert a new element in a priority-based position.
 

Implementation of each STL container:

(1) vector
Internal data structure: array.
Each element is randomly accessed. The time required is a constant.
The time required to add or delete an element at the end is irrelevant to the number of elements. The time required to add or delete an element at the beginning or in the middle changes linearly with the number of elements.
You can dynamically add or remove elements and manage the memory automatically. However, you can use the reserve () member function to manage the memory.
The iterator of the vector will become invalid when the memory is re-allocated (the elements it points to are no longer the same before and after the operation ). When more than capacity ()-size () elements are inserted into the vector, the memory will be re-allocated and all iterators will become invalid; otherwise, the iterator pointing to any element after the current element fails. When an element is deleted, the iterator pointing to any element after the element is deleted becomes invalid.

(2) deque
Internal data structure: array.
Each element is randomly accessed. The time required is a constant.
The time required to add an element at the beginning and end is irrelevant to the number of elements. The time required to add or delete an element in the middle changes linearly with the number of elements.
Elements can be dynamically added or removed, and memory management is completed automatically. member functions used for memory management are not provided.
Adding any element will invalidate the deque iterator. Deleting an element in the middle of deque will invalidate the iterator. When a deque header or tail deletes an element, only the iterator pointing to the element fails.

(3) list
Internal data structure: Bidirectional Ring linked list.
You cannot randomly access an element.
Bidirectional traversal is supported.
The time required to add or delete an element at the beginning, end, or in the middle is constant.
You can dynamically add or remove elements and manage the memory automatically.
Adding any element will not invalidate the iterator. When an element is deleted, other iterators will not expire except the iterator pointing to the currently deleted element.

(4) slist
Internal data structure: one-way linked list.
It cannot be traversed in two directions. It can only be traversed from front to back.
Other features are similar to list.

(5) stack
Adapter, which can convert any type of sequence container into a stack. Generally, deque is used as the supported sequence container.
The element can only be post-in, first-out (LIFO ).
The entire stack cannot be traversed.

(6) queue
It can convert any type of sequence container into a queue. Generally, deque is used as the supported sequence container.
The element can only be FIFO ).
The entire queue cannot be traversed.

(7) priority_queue
It can convert any type of sequence container into a priority queue. Generally, vector is used as the underlying storage mode.
Only the first element can be accessed, and the whole priority_queue cannot be traversed.
The first element is always the element with the highest priority.

(8) set
The keys and values are equal.
The key is unique.
Elements are arranged in ascending order by default.
If the element to which the iterator points is deleted, the iterator becomes invalid. Any other operations to add or delete elements will not invalidate the iterator.

(9) multiset
The key may not be unique.
Other features are the same as those of set.

(10) hash_set
Compared with set, the elements in it are not necessarily sorted, but allocated by the hash function used. It can provide faster search speed (of course, related to the hash function ).
Other features are the same as those of set.

(11) hash_multiset
The key may not be unique.
Other features are the same as hash_set.

(12) map
The key is unique.
The elements are sorted in ascending order by default.
If the element to which the iterator points is deleted, the iterator becomes invalid. Any other operations to add or delete elements will not invalidate the iterator.

(13) multimap
The key may not be unique.
Other features are the same as those of map.

(14) hash_map
Compared with map, the elements in it are not necessarily sorted by key values, but are allocated according to the hash function used, it provides a faster search speed (of course, also related to the hash function ).
Other features are the same as those of map.

(15) hash_multimap
The key may not be unique.
Other features are the same as hash_map.


C ++ STL container selection

Some common container selection problems
? Do you need to insert new elements anywhere in the container?
If needed, select a sequence container; no way to associate the container.
? Are you concerned about how elements in the container are sorted?
If you do not care about it, the hash container is a feasible solution. Otherwise, you must avoid the hash container.
? Must the container you selected be part of the standard C ++?
If yes, the hash container, slist, and rope are excluded.
? What type of iterator do you need?
If they must be random accessors, the selection of containers is limited to vector, deque, and string. Maybe you can also consider rope. If two-way iterators are required, you must avoid a common implementation of slist and hash containers.
? When an element is inserted or deleted, is it important to avoid moving the original element in the container?
If yes, it is necessary to avoid consecutive memory containers.
? Is the data layout in the container compatible with C?
To be compatible, you can only select a vector container.
? Is the search speed of elements a key consideration?
If yes, consider the hash container, the sorted vector, and the standard associated container-maybe this is the priority.
? If the reference counting technology is used inside the container, do you mind?
If yes, avoid using string, because many string implementations use reference count. You also need to avoid this because the authoritative Rope implementation is based on reference counting. Of course, you need some way to represent a string. You can consider vector <char>.
? Do you need transaction semantics (transactional semantics) for insert and delete operations? That is to say, do you need the rollback capability when the insert or delete operation fails?
If necessary, you need to use a node-based container. If the insert operation on multiple elements requires transaction semantics, You need to select list, because in the standard container, only list provides transaction semantics for the insert operation on multiple elements.
? Do you need to make the iterator, pointer, and reference the least number of invalid times?
If so, you need to use a node-based container, because the insert and delete operations on these types of containers never invalidate the iterator, pointer, and reference (unless they point to an element you are deleting ). Insert and delete operations on the continuous memory container will generally invalidate the iterator, pointer, and reference pointing to the container.
? If the sequent container iterator is of the random access iterator type, and no deletion operation occurs, and the insert operation only occurs at the end of the container, the pointer and reference pointing to the data will not become invalid. Is this container helpful to you?
This is a very special situation, but if you are facing this situation, deque is the container you want. (Interestingly, when the insert operation only occurs at the end of the container, the deque iterator may become invalid. Deque is the only iterator that may become invalid and the pointer and reference will not become invalid STL standard containers .)

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.