Deep analysis of common container _c language in C + + STL

Source: Internet
Author: User

The STL is a very important template in C/s + + development, and the various containers defined in it are very convenient for us all to use. Below, we will talk about some commonly used containers. Here we do not involve the basic operation of the container and so on, just to discuss the individual containers of their respective characteristics. Common containers in STL include: sequential containers (vector, deque, list), associative containers (map, set), Container adapters (queue, STAC).

1. Sequential container

(1) Vector
Vector is a dynamic array that has contiguous storage space in memory and supports fast random access. Because of the continuous storage space, the efficiency is slower in the insert and delete operations. Vector has multiple constructors, the default constructor is to construct a memory space with an initial length of 0, and the allocated memory space is dynamically increasing in multiples of 2, that is, the memory space growth is in accordance with 20,21,22,23 ... growth, in the process of push_back, If the allocated memory space is found to be insufficient, redistribution of contiguous memory space, which is twice times the size of the current contiguous space, and then copying elements from the original space into the new space, is much more performance-intensive, especially when the elements are not internal data (the non internal data is often constructed and the copy constructor is quite complex). Another common problem with vectors is the clear operation. The clear function simply zeroes the size of the vector, but the elements in the vector are not eliminated in memory, so the use of the vector will result in more memory consumption, resulting in memory leaks, which is now frequently used as a swap function to resolve:

Copy Code code as follows:

Vector<int> V;
V.push_back (1);
V.push_back (2);
V.push_back (1);
V.push_back (2);
Vector<int> (). Swap (V);
or V.swap (vector<int> ());

With the swap function, swap with the temporary object so that the memory of the V object is the memory of the temporary object, while the temporary object's memory is the memory of the V object. After the swap, the temporary object disappears and frees up memory.

(2) Deque
Deque are similar to vectors and support fast random access. The biggest difference is that vectors can only insert data at the end, while Deque supports inserting data on both ends. Deque's memory space distribution is a continuous small piece, the small pieces are linked with a linked list, in fact, there is a map inside the pointer. The redistribution of deque space is faster than vector, and the original elements do not need to be copied after the space is redistributed.

(3) List
List is a two-way list, so its memory space can be discontinuous, with pointers to data access, which makes random storage of the list very inefficient, so the list does not provide an overload of the [] operator. But the list can well support the insertion and deletion of any place, just move the corresponding pointer.

(4) In actual use, how to choose which of these three containers, should be based on your needs, the general should follow the following principles:
1 If you need efficient and immediate access without caring about the efficiency of insertion and deletion, use vector
2 If you need a large number of inserts and deletes, but do not care about the immediate access, you should use the list
3 If you need to immediately access, and care about both the insertion and deletion of data, you should use the Deque

2. Related containers

The

(1) Map
Map is an associative container that maps the corresponding value with a unique keyword, that is, the Key-value feature. Map built a red-black tree (a self-balanced binary tree), this tree has the function of automatic data sorting, so all the data within the map is ordered, in the form of two-fork tree organization.

This is the template for map:
Template < class Key, class T, Class Compare= Less<key>, Class allocator= allocator< Pair<const key,t> > > class map;

As we can see from the template, the map is structured in a certain order. The insert and delete efficiency of a map is higher than that of other sequences because, for the associated container, you do not need to copy and move the memory, just the movement of the pointer. Because each of the map's data corresponds to a node on the red-black tree, this node takes up 16 bytes without saving your data, a parent pointer, a pointer to the child, and an enumeration value (marked with red and black), so one of the drawbacks of map is that it takes up more memory space.

(2) Set
Set is also a kind of correlation container, it is similar to map, the bottom layer uses the red black tree implementation, inserts the deletion operation only then moves the pointer, does not involve the memory movement and the copy, therefore the efficiency is high. The elements in set are unique, and the elements are sorted in ascending order by default. So in set, you can't change the value of the element directly, because that will disrupt the original correct order, to change the element value must first delete the old elements, and then insert the new elements. Any operation function that does not provide a direct access element can only be indirectly accessed through an iterator.

Set Template prototype:
Template <class key, Class Compare=class<key>, Class Alloc=stl_default_allocator (key) > class set;

The set supports operations on some sets, such as the intersection (set_intersection), Difference (set_difference), and (set_union) of the set, and the symmetry difference (set_symmetric_difference).

3. Container Adapter

(1) Queue
Queues are a queue that implements advanced first out functionality, and queue is not a standard STL container, but is based on standard STL containers. The queue is encapsulated on a deque basis. Choosing deque instead of a vector is because deque frees up space when deleting elements, and does not need to copy all elements when requesting space again.

The template is:
Template < TYPENAME _sequence= "DEQUE<_TP" Typeneam _tp,> > class queue;

The

(2) stack
stack is an advanced feature that, like the queue, is internally encapsulated deque, which is why it is called a container adapter (pure guesswork). It does not directly maintain the template class of the controlled sequence, but rather the container object it stores to implement all the functions for it. Stack's source code principles and implementations are the same as the queue.

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.