Summary of c ++ STL containers: vertor and list applications

Source: Internet
Author: User

STL provides six components that can be combined and used together

1. containers: various data structures, such as vertor, list, deque, set, and map. STL containers are a class template.

2. algorithms (algorithms): various algorithms such as sort, search, copy, and earse. STL is a function template.

3. iterators: act as the glue between containers and algorithms. It is called a generic pointer ". All STL containers have their own exclusive iterators.

4. functors: similar behavior functions can be used as some algorithms. From the implementation point of view, the imitation function is a class or class template with operator () reloaded.

5. adapters: a tool used to modify containers, simulate functions, or iterate tools. For example, queue and stack

6. configurator: responsible for space configuration and management. The Configurator is a class template that implements dynamic space allocation, space management, and space release.

STL is built on generalization. The array is generalized to a container and parameterized the types of the contained objects. Function generalization is an algorithm that parameterized the type of the iterator used. The pointer is generalized as an iterator and parameterized the type of the object to which it points.

Vector, string, deque, and list are called standard sequence containers,

Set, multiset, map, and multimap are standard associated containers.

Non-standard sequence containers slist and rope. Slist is a one-way linked list, and rope is essentially a heavy string.

Non-standard associated containers hash_set, hash_multiset, hash_map, and hash_multimap.

Standard non-STL containers, including arrays, bitset, valarray, stack, queue, and priority_queue.

The iterator is divided into five types:

The input iterator is a read-only iterator that can only be read once at each iteration position.

The output iterator is a write-only iterator that can only be written once at each iteration position.

The input and output iterators are modeled as read and write input and output streams (for example, files ).

The forward iterator has the ability to input and output the iterator, but they can read or write a location repeatedly.

Two-way iterators are like forward iterators, and they can be as easy as forward. Standard associated containers provide two-way iterators. List also has.

Continuous memory containers (also called array-based containers) store their elements in one or more (dynamically allocated) memory blocks. If a new element is found or the existing element is deleted, other elements in the same memory block must move up or down to provide space for the new element or fill the space occupied by the original deleted element. This movement affects efficiency and exceptional security. The standard continuous memory containers are vector, string, and deque. Non-standard rope is also a continuous memory container.

Node-based containers store only one element in each memory block (dynamically allocated. The insertion or deletion of container elements only affects the pointer to the node, not the content of the node. So when something is inserted or deleted, the element value does not need to be moved. Containers represented as linked lists, such as list and slist, are node-based and all standard associated containers are also (their typical implementation is the Balance Tree ). Non-standard hash containers use different node-based implementations.

1. vector

Like arrays, vector has a continuous memory space and the starting address remains unchanged. Therefore, it supports Random Access (that is, using the [] operator to access the elements ), however, because its memory space is continuous, insertion and deletion in the middle will result in copying of memory blocks (complexity is O (n). In addition, when the memory space after the array is insufficient, you need to apply for a memory that is large enough to copy the memory. These greatly affect the efficiency of vector.

Vector is not a data type, but a class template. It can be used to define any number of data types. Each element of the vector type specifies the type of elements it saves. Therefore, both vector <int> and vector <string> are data types.

Definition and initialization of a vector object

Vector <T> v1;

Objects whose vector type is T are saved. The default constructor v1 is null.

Vector <T> v2 (v1 );

V2 is a copy of v1.

Vector <T> v3 (n, I );

V3 contains n elements whose values are I.

Vector <int> ivec4 (10,-1); // 10 elements, each initialized to-1

Vector <string> svec (10, "hi! "); // 10 strings, each initialized to" hi! "

Vector operations

V. empty ()

If v is null, true is returned; otherwise, false is returned.

V. size ()

Returns the number of elements in v.

V. push_back (t)

Add an element whose value is t at the end of v.

V [n]

Returns the element with the position n in v.

V1 = v2

Replace element v1 with a copy of element v2.

V1 = v2

Returns true If v1 and v2 are equal.

! =, <, <=,>,> =

Maintain the meaning of these operators.

Add element to vector:

Copy codeThe Code is as follows: string word;

Vector <string> text; // empty vector

While (cin> word ){

Text. push_back (word); // append word to text

Subscript operation of vector:

For (vector <int >:: size_type ix = 0; ix! = Ivec. size (); ++ ix)

Ivec [ix] = 0;

Vector iterator

Each container defines a function named begin and end for returning the iterator. If the container contains elements, the iterator returned by begin points to the first element:

Copy codeThe Code is as follows: vector <int >:: iterator iter = ivec. begin ();

The iterator returned by the end operation points to the "next to the end element" of the vector ". It is usually called the off-the-end iterator, indicating that it points to a nonexistent element. If the vector is empty, the iterator returned by begin is the same as the iterator returned by end.Copy codeThe Code is as follows: for (vector <int>: iterator iter = ivec. begin (); iter! = Ivec. end (); ++ iter)

* Iter = 0; // set element to which iter refers to 0


The previous program used vector: iterator to change the element value in the vector. Each container type also defines a type named const_iterator, which can only access elements in the container but cannot change its value.

Copy codeThe Code is as follows: for (vector <string >:const_iterator iter = text. begin (); iter! = Text. end (); ++ iter)

* Iter = ""; // error: * iter is const

2. list

A list is implemented by a two-way linked list in the data structure, so its memory space can be discontinuous. Therefore, data can only be accessed through pointers. This feature makes random access very inefficient and requires traversing intermediate elements to search for complexity O (n ), therefore, it does not provide an overload of the [] operator. However, due to the characteristics of the linked list, it supports deletion and insertion anywhere with good efficiency.

List: iterator and vector: iterator have some differences:

Copy codeThe Code is as follows: # include <iostream>
# Include <vector>
# Include <list>
Using namespace std;

Int main (void)
Vector <int> v;
List <int> l;

For (int I = 0; I <8; I ++) // Add elements to v and l respectively.
V. push_back (I );
L. push_back (I );

Cout <"v [2] =" <v [2] <endl;
// Cout <"l [2] =" <l [2] <endl; // compilation error. list is not overloaded []
Cout <(v. begin () <v. end () <endl;
// Cout <(l. begin () <l. end () <endl; // compilation error. list: iterator is not overloaded <or>
Cout <* (v. begin () + 1) <endl;

Vector <int>: iterator itv = v. begin ();
List <int>: iterator itl = l. begin ();
Itv = itv + 2;
// Itl = itl + 2; // compilation error. list: iterator is not overloaded +
Itl ++; // list: The iterator loads ++ and can only use ++ for iterative access.
Cout <* itv <endl;
Cout <* itl <endl;

Return 0;

Vector has a continuous memory space and supports random access. Therefore, vector <int>: iterator supports operators such as "+", "+ =", and "<.

The memory space of the list can be discontinuous, and it does not support random access. Therefore, list <int> :: iterator does not support operator operations such as "+", "+ =", and "<". Therefore, Code 20 and 26 May Have compilation errors. Only "++" can be used for iteration, for example, line 27 of code. itl ++ can be moved twice. In addition, the [] operator is not supported for list. Therefore, a compilation error occurs in line 18 of the Code.

In short, if efficient instant access is required, and the insertion and deletion efficiency is not concerned, the vector is used. If a large number of inserts and deletions are required, rather than instant access, the list should be used.

Vector has a continuous memory space, so it supports random access. If you need efficient instant access without having to care about the efficiency of insertion and deletion, use vector.

List has a discontinuous memory space, so it supports random access. If you need a large number of inserts and deletes, but do not care about instant access, you should use list.You can select the deque data structure when most inserts and deletes occur at the header or end of the sequence.

Related Article

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: 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.