C + + STL container summary: Vertor and list Application _c language

Source: Internet
Author: User
Tags arrays data structures

STL provides six major components that can be combined

1, container (containers): a variety of data structures, such as vertor,list,deque,set,map. From the perspective of implementation, the STL container is a class template

2, Algorithm (algorithms): various algorithms such as Sort,search,copy,earse. STL algorithm is a function template.

3, iterator (iterators): act as a glue between the container and the algorithm, is called "Generic pointer." All STL containers have their own dedicated iterators.

4, Imitation function (functors): behavior Similar functions, can be used as an algorithm for some strategies. From an implementation point of view, an affine function is a class or class template that overloads the operator ().

5. Adapter (adapters): a thing used to modify a container or an excuse for an imitation function or an iterator. such as queue and stack

6, Configurator (allocators): responsible for the configuration and management of space. The Configurator is a class template that realizes dynamic spatial allocation, space management and space release.

The STL is based on generalization. The array is generalized to a container, and the type of the contained object is parameterized. function generalization as an algorithm, parameterized the type of iterator used. The pointer is generalized to an iterator, parameterized by the type of object being pointed to.

Vector, String, deque, and list are called standard sequence containers.

Set, Multiset, map, and multimap are standard associative containers.

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

Non-standard associative containers hash_set, Hash_multiset, Hash_map and Hash_multimap.

Standard non-STL containers, including arrays, Bitset, Valarray, Stack, queue, and priority_queue.

Iterators are divided into five categories:

An input iterator is a read-only iterator that can only be read once per iteration position.

An output iterator is a write-only iterator that can be written once per iteration position.

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

Forward iterators have the ability to input and output iterators, but they can read or write a location over and over again.

Bidirectional iterators are like forward iterators, except that their retreat can be as easy as advancing. Standard associative containers provide bidirectional iterators. List also has.

A contiguous memory container (also called an array-based container) holds its elements in one or more (dynamically allocated) blocks of memory. If a new element is checked in or the stored element is deleted, other elements in the same memory block must be moved 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 safety. The standard contiguous memory container is vector, string, and deque. Non-standard rope are also contiguous memory containers.

A node-based container saves only one element in each block of memory (dynamically allocated). The insertion or deletion of a container element affects only the pointer to the node, not the node's own content. So when something is inserted or deleted, the element value does not need to be moved. Containers that behave as lists-such as list and slist--are nodes based, and all standard associative containers are (their typical implementations are the balanced tree). Non-standard hash containers use different node based implementations.

1. Vector

Like vectors and arrays, it has a contiguous memory space, and the starting address is unchanged, so it is very good to support random access (that is, use the [] operator to access the elements), but because its memory space is continuous, so inserting and deleting in the middle will cause the memory block copy (complexity is O (n) , in addition, when there is not enough memory space after the array, you will need to reapply a large enough memory and make a copy of the memory. These have greatly affected the vector's efficiency.

A vector is not a data type, but rather a class template that can be used to define any number of data types. Each of the vector types specifies the type of element in which it is saved. So,vector<int> and vector <string> are all data types.

Definition and initialization of vector objects

Vector<t> v1;

Vector holds an object of type T. The default constructor v1 is empty.

Vector<T> v2(v1);

V2 is a copy of v1.

Vector<T> v3(n, i);

V3 contains an element with n values of I.



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

Vector<string> Svec ("hi!"); strings, each initialized to "hi!"

The operation of the vector

V.empty()

Returns True if V is empty, otherwise returns false.

V. Size()

Returns the number of elements in V.

V. Push_back(t)

Add an element with a value of t at the end of V .

v[N]

Returns an element in V with position n .

V1 = v2

Replace the V1 element with a copy of the element in V2.

V1 = = v2

returns True if the V1 is equal to the V2 .

!=, <=, >=

Keep the usual meanings of these operators.

To add an element to a vector:

Copy Code code as follows:

string Word;

vector<string> text; Empty vector

while (CIN >> word) {

Text.push_back (word); Append Word to Text

}
Vector's subscript operation:


for (Vector<int>::size_type IX = 0; IX!= ivec.size (); ++ix)

Ivec[ix] = 0;

Vector iterator

Each container defines a pair of functions named Begin and end, which is used to return the iterator. If there are elements in the container, the iterator returned by begin points to the first element:

Copy Code code as follows:

Vector<int>::iterator iter = Ivec.begin ();

The iterator returned by the end operation points to the next of the vector's "terminal element." It is often called a off-the-end iterator, indicating that it points to an element that does not exist. If the vector is empty, the iterator returned by begin is the same as the iterator returned by end.
Copy Code code as follows:

for (Vector<int>::iterator iter = Ivec.begin (); Iter!= ivec.end (); ++iter)

*iter = 0; Set element to which ITER refers to 0

Const_iterator

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

Copy Code code as follows:

for (Vector<string>::const_iterator iter = Text.begin (); ITER!= text.end (); + iter)

*iter = ""; Error: *iter is const

2, List

The list is implemented by a two-way list in the data structure, so its memory space can be discontinuous. Therefore, the data can only be accessed through the pointer, which makes its random access very inefficient, needs to traverse the middle element and search for complexity O (n), so it does not provide an overload of the [] operator. However, because of the characteristics of the linked list, it can support the deletion and insertion of any place with good efficiency.

Some differences between List::iterator and Vector::iterator:

Copy Code code 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 does not overload []
cout << (V.begin () < V.end ()) << Endl;
cout << (L.begin () < L.end ()) << Endl; Compilation error, List::iterator no overload < 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 no overload +
itl++;itl++; + + is overloaded in list::iterator and can only be iterated using + +.
cout << *itv << Endl;
cout << *itl << Endl;

return 0;
}

Because Vector has a continuous memory space, can very good support random access, so vector<int>::iterator support "+", "+ +", "<" operators.

And the list of memory space can be discontinuous, it does not support random access, so list<int>::iterator does not support "+", "+ +", "<" operator operations, so code 20, 26 lines have compile errors. You can only use "+ +" for iterations, such as code 27 lines, which use two times itl++ to move ITL. There is also a list that does not support the [] operator, so there is a compile error on line 18.

In short, if you need efficient, immediate access, but you don't care about the efficiency of insertions and deletions, use vectors, and if you need a lot of insertions and deletions, and you don't care about immediate access, you should use list.

Vector has a continuous memory space, so it supports random access, and if you need efficient and immediate access without caring about the efficiency of insertions and deletions, use vectors.

List has a discrete amount of memory space, so it supports random access, and if you need a lot of insertions and deletions without concern for immediate access, use list. you can choose to deque this data structure when most inserts and deletions occur at the head or end of a 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: 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.