Overview of STL Containers

Source: Internet
Author: User
Tags map class

I. Definition of containers

On the data store, there is an object type, which can hold other objects or pointers to other pairs of images, which are called containers. In C + +, a container is a generic data structure that can hold a variety of data types, and is a class template. A container is an object that holds other objects, which, of course, is a simple understanding, and this "object" also contains a series of methods for dealing with "other objects".

Two. Types of containers

Common containers in STL include: Sequence container (vector, deque, list), associative container (map, set), container adapter (queue, Stac).

1. Sequence container: a linear table with sequential relationships between the elements and a sequential cluster of linear structures. Each element in a sequential container has a fixed position, unless the position is changed by a delete or insert operation. The order of the elements in a sequential container is independent of the element value, but is determined by the order in which the elements are added to the container. The sequence container includes: vector, List, deque (queue).
2. Associative containers: Associative containers are non-linear tree structures, and more accurately, two-fork tree structures. There is no strict physical order between the elements, which means that the elements do not have a logical order in the container when the elements are placed into the container. But associative containers provide another feature that is ordered based on the characteristics of the elements, so that iterators can "sequentially" acquire elements based on their characteristics. Elements are ordered collections, which are sorted in ascending order by default when inserted. The associated containers are: Map (collection), set (map), Multimap (Multiset), Multiset (Multimap).
3. Container adapter: Essentially, an adapter is a mechanism that makes a different behavior similar to the behavior of another thing. A container adapter enables an existing container type to work in a different type of abstraction. The adapter is the interface of the container, which itself cannot save the element directly, its mechanism to save the element is to invoke another sequential container to implement, that is, the adapter can be thought of as "it holds a container, this container to save all the elements." The STL contains three types of adapters: stack stack, queue queues, and priority queue priority_queue.

The container class automatically requests and frees memory, so new and delete operations are not required.

Three. Sequence container

The Sequence container maintains the order of the inserted elements that you specify.

1.vector

vectorThe container behaves like an array, but can grow automatically as required. It can be randomly accessed, stored continuously, and very flexible in length. For these and other reasons, vector it is the preferred sequence container for most applications. If you are unsure which sequence container to use, use the vector first! For more information, see Vector classes .

Vector Dynamic Array header file <vetor>

The elements are stored continuously in memory.

Random access Time: constant time (because the address can be accessed directly by subscript).

The trailing and adding elements are usually constant time (normal is constant time, if the number of elements allocated by default is exceeded, the storage space will be reallocated and more time will be consumed).

Adding or removing elements in the middle or head: O (n) (the position of other elements will be moved).

Iterator type: Random access (supports subscript access, random move, Example: A[i]).

Query time: O (n) (because there is no sorting, only the current search, efficiency is low).

Vector can be seen in the middle or the head and other elements of low performance.

Benefits: Memory and C are fully compatible, efficient random access, space saving

Cons: Internal insert Delete elements are expensive, dynamic size check their capacity needs to request a large amount of memory to make a large number of copies .

constructor function:

Vector ( ), vector (int  n), vector (intconst// n elements initialized to a /
/ Initialize content consistent with the interval [first,last] on other containers

Common member functions:

void Pop_back (); void push_back (const T &val); int  && Back ();
2.deque

dequeThe (double-ended queue) container supports quick insertions and deletions at the start and end points of the container. It has vector the advantage of random access and flexible length, but does not have continuity. For more information, see the Deque class.

Elements are stored continuously in memory (the container of contiguous memory has an obvious disadvantage, that is, when new elements are inserted or old elements are deleted, in order to make room for new elements or to fill the vacancy of old elements, the other data in the same piece of memory needs to be shifted overall, the copy cost of this shift is sometimes very large. Deque is actually allocated to different blocks of memory, through the linked list of memory blocks together, and then continuous storage, is the list and vector compromise.

Random access Time: Constant time (second only to vector, because there may be a scenario where the tail memory position precedes the head).

Adding or deleting elements at both ends is usually a constant time. (Deque does not have the capacity of a vector and does not need to reallocate memory space.) This is because deque is composed of dynamically allocated contiguous spaces, or buffers, that can be added to a new space at any time. It doesn't have to be like a vector that "re-allocates twice times as much space as the old space, then copies the elements and frees up the old space." When the buffer is reallocated, the time-consuming increase).

Insert in middle: time complexity is high.

Iterator type: Random access (less efficient than vector).

Query time: O (n) (for the same reason).

advantages : Efficient random access, internal insertion Delete elements efficient, push at both ends, pop efficiency is high

cons : High memory consumption

3.list

listA container is a doubly linked list that enables bidirectional access, quick Insert, and quick Delete anywhere within the container, but you cannot randomly access the elements in this container. For more information, see List class.

The element is not contiguous in memory (because the pointer can get the address of the front and back elements), so random access is not supported .

Delete element time at any location: constant time.

Query time: O (n) (for the same reason).

Iterator type: bidirectional (subscript access not supported, iterator-less comparison operator, and +-operator)

Pros: Insert delete element in any position constant time complexity, two container fusion is a constant time complexity

Cons: Random access is not supported and more storage space is consumed than vectors

Common member functions: (note that these are list-unique in the sequential container)

Push_frontpop_frontsort    // Stlsort algorithm not supported Removeuniquemergereversesplice

In particular, the list's sort function has no parameters and compare two versions

list<t> Classnameclassname.sort (Compare);   // Compare Custom classname.sort ();
4.array

arrayThe container has vector some advantages, but the length is not flexible enough. For more information, see the array class.

5.forward_list

forward_listThe container is a single linked list, list with a forward access version. For more information, see the Forward_list class.

Four. Associative containers

In the associative container, the elements are inserted in a predefined order, for example, by ascending sort. Unordered associative containers are also available. Associative containers can be divided into two subsets: mappings and set of groups.

1.map

map, sometimes called a dictionary, that contains key/value pairs. The key is used to sort the sequence, and the value is associated with the key. For example, map there may be many keys (representing each unique word in the text) and corresponding values (representing the number of occurrences of each word in the text). mapthe unordered version is unordered_map . For more information, see the Map class and the Unordered_map class.

2.set

setOnly the container for each element is sorted in ascending order, and the value is also the key. setthe unordered version is unordered_set . For more information, see Set class and Unordered_set class.

3. Other

mapAnd set both allow only one instance of the key or element to be inserted into the container. If you need more than one instance of an element, use multimap or multiset . The unordered version is the unordered_multimap and unordered_multiset . For more information, see Multi-mapping classes, UNORDERED_MULTIMAP classes, multi-collection classes, and Unordered_multiset classes.

Ordered mappings and group sets support bidirectional iterators, and their unordered replicas support forward iterators. For more information, see iterators

heterogeneous lookups in associative containers (c++14)

Sorting associative containers (mappings, Multimap, sets, and multiset) now support heterogeneous lookups, which means that you will no longer need to pass the exact same object type as a key or element in a member function (such as find() and lower_bound() ). Instead, you can pass a type that defines the overloads operator< to enable comparison of the key types.

Five. Container Adapter

A container adapter is a variant of a sequence container or an associative container, which restricts the interface for simplicity of clarity.

The container adapter does not support iterators.

queueThe container follows the FIFO (first-out) semantics. The first element pushes -that is, the insert queue-is the first to eject --that is, removed from the queue. For more information, see Queue classes.

priority_queueContainers are also organized so that elements with the highest values always rank first in the queue. For more information, see the Priority_queue class.

stackThe container follows the LIFO (LIFO) semantics. The last pushed element on the stack will be the first one popped. For more information, see Stack class.

Because the container adapter does not support iterators, it cannot be used with the STL algorithm. For more information, see Algorithms.

Six. Summary
    • If random access is required, use the vector
    • If the number of stored elements is known, use the vector
    • You need to randomly insert a delete anywhere, using the list
    • Delete elements are often inserted at the end of the container's header, using deque
    • Element structure complex with list, you can also use vectors to store pointers (need extra effort to maintain memory), to see the requirements
    • If the operation is based on a key value, use the Set/map
    • If you need a regular search, use Map/set

Six. References

1.https://msdn.microsoft.com/zh-cn/library/1fe2x6kt.aspx

2.70241850

3.49964299

4.https://juejin.im/post/5a5607166fb9a01cb256d501

Overview of STL 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.