STL container efficiency comparison

[Original: http://www.oschina.net/question/723629_65432 ]

1、vector

Variable-length one-dimensional arrays, memory blocks stored continuously, reserved memory, and memory allocated in the heap;

Support [] operation, efficient random access;

When adding elements at the end, there is generally no need to allocate memory space, and the speed is fast; it is inefficient to copy memory in the middle or when elements are started to be manipulated;

The reason a vector is efficient is that more memory is allocated than the elements it holds, and memory reconfiguration takes a lot of time;

Note: need efficient random access and don't care about insertion and deletion use vector.

 

2、list

Doubly linked list, the memory space may be discontinuous, no reserved memory, and memory is allocated in the heap;

Does not support random access , the access time of the start and end elements is fast , and other elements are O(n) ;

It is faster to insert and delete elements at any position, and the insertion and deletion operations will not invalidate each pointer, reference, and iterator of other elements;

Note: lots of insertions and deletions, regardless of random access use list.

 

3、

Double-ended queue, memory is allocated on the heap, a heap holds several elements, and pointers are used to connect between heaps;

Supports the [] operation, which is faster to insert and delete elements at the beginning and end, and slower to insert and delete in the middle, such as the combination of list and vector ;

Note: Use deque as a compromise between caring about insertions and deletions and caring about random access.

 

4、set&multiset

Sorted set, using balanced binary tree storage, sorts the data in the set according to the given sorting rule (the default is less sorting);

Duplicate elements are not allowed in set, and duplicate elements are run in multiset;

Both do not support direct access to elements;

Because it is automatic sorting, the speed of finding elements is relatively fast;
you cannot directly change the element value, otherwise the original correct order will be disrupted, you must first delete the old element, and then insert the new element.

 

5、map&multimap

Dictionary library, one value is mapped to another value, stored in a balanced binary tree, and the key values ​​in the map are sorted according to the given sorting rules;

The key value in the map is not allowed to be repeated, and the key in the multimap is allowed to be repeated;

It is faster to find elements based on known key values;

Insertion and deletion operations are slow.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588819&siteId=291194637