C + + STL summary one: Vertor and List

Source: Internet
Author: User

STL provides six components that can be combined to apply

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

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

3, Iterators (iterators): Play between the container and the algorithm of the glue, is called "Generic pointer." All STL containers have their own dedicated iterators.

4, functor (functors): behaves like a function, can be used as some strategy of the algorithm. From an implementation point of view, the functor is a class or class template that overloads the operator ().

5, adapter (adapters): An excuse for modifying a container or an imitation function or an iterator. such as queue and stack

6, Configurator (allocators): Responsible for the configuration and management of space. 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 the type of the contained object is parameterized. function generalization is an algorithm that parameterize the type of iterator used. Pointer generalization is an iterator that parameterize the type of object being pointed to.

Vectors, strings, deque, and lists are called standard sequence containers,

set, Multiset, map, and Multimap are standard associative container.

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

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

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

Iterators are divided into five categories:

an input iterator is a read-only iteration where each iteration position can be read only once generation of converters.

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

input and output iterators are molded into read and write inputs and outputs streams (for example, files).

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

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

contiguous memory Container (also called An array-based container holds their elements in one or more (dynamically allocated) chunks of memory. If a new element is checked in or the saved element is deleted, the other elements in the same block of memory must move up or down to provide the new element with empty space or fill in the original deleted element. This movement affects efficiency and exceptional security . The standard contiguous memory container is vector, string, and deque. Non-standard rope are also contiguous memory containers.

node-based containers only one element is saved in each block of memory (dynamic allocation). 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 linked lists-for example , list and slist--are node-based, and all standard associative containers are (their typical implementation is a balanced tree). Non-standard hash containers make use of different node-based implementations.

1. Vector

Vector and array similar, it has a contiguous memory space, and the starting address is unchanged, so it can very well support random access (that is, using the [] operator to access the elements), but because its memory space is continuous, so in the middle of the insert and delete will cause a copy of the memory block (the complexity is O (n) In addition, when there is not enough memory space behind the array, you need to re-request a chunk of memory that is large enough to make a copy of the memory. These have greatly affected the efficiency of vectors.

Vector is not a data type, but just a class template that can be used to define any number of data types. Each of the vector types specifies the type of the element it holds. So,vector<int> and vector <string> are data types.

Definition and initialization of vector objects

Vector<t> v1;

The 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);

The v3 contains n elements with a value of I.

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

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

Operation of the Vector

V.empty ()

Returns true if V is null, otherwise false is returned.

V.size ()

Returns the number of elements in V.

V.push_back (t)

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

V[n]

Returns an element of position N in v.

V1 = V2

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

V1 = = V2

Returns true if V1 is equal to V2.

! =, <, <=, >=

Keep these operators in their customary meaning.

To add an element to a vector :

string word;vector<string> text;        // empty vector while (cin >> word) {     text.push_back(word);  // append word to text}

  Vector Subscript Operation:

for(vector<int>::size_type ix = 0; ix != ivec.size(); ++ix)    ivec[ix] = 0;

  

Vector iterators

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

vector<int>::iterator iter = ivec.begin();

The iterator returned by the end operation points to the next "end element of the vector". is often referred to as an out-of-end iterator (Off-the-end iterator), indicating that it points to a non-existent element. If the vector is empty, begin returns an iterator that is the same as the iterator returned by end.

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 value of the elements in the vector. Each container type also defines a type named Const_iterator that can access only the elements inside the container, but cannot change its value.

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 doubly linked list in a data structure, so its memory space can be discontinuous. Therefore, the data can only be accessed through pointers, which makes its random access variable very inefficient, the need to traverse intermediate elements, search complexity O (n), so it does not provide overloading of the [] operator. However, due to the characteristics of the list, it can be very efficient to support the deletion and insertion anywhere.

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

#include <iostream>#include <vector>#include <list>usingnamespacestd;intmain( void){        vector<int> v;         list<int> l;                for(inti=0; i<8; i++)     //往v和l中分别添加元素        {                v.push_back(i);                l.push_back(i);        }                cout << "v[2] = "<< v[2] << endl;        //cout << "l[2] = " << l[2] << endl;       //编译错误,list没有重载[]        cout << (v.begin() < v.end()) << endl;        //cout << (l.begin() < l.end()) << endl;   //编译错误,list::iterator没有重载<或>        cout << *(v.begin() + 1) << endl;                 vector<int>::iterator itv = v.begin();        list<int>::iterator itl = l.begin();        itv = itv + 2;        //itl = itl + 2;                  //编译错误,list::iterator没有重载+        itl++;itl++;                    //list::iterator中重载了++,只能使用++进行迭代访问。        cout << *itv << endl;        cout << *itl << endl;        return0;}

Because Vector has a contiguous memory space and can support random access very well, Vector<int>::iterator supports "+", "+ =", "<" operators.
And the list of memory space can be discontinuous, it does not support random access, so list<int>::iterator does not support "+", "+ =", "<" and other operators, so code 20, 26 rows have compile errors. You can only use "+ +" to iterate, such as code 27 lines, using two times itl++ to move the ITL. There is also a list that does not support the [] operator, so there is a compilation error in code 18 line.
In short, if you need efficient and immediate access, instead of the efficiency of insertion and deletion, use vectors, if you need a lot of insertions and deletions, and you don't care about access, you should use list.

Vector has a contiguous memory space, so it supports random access, and if you need efficient immediate access, instead of the efficiency of insertions and deletions, use vectors.
The list has a discrete memory space, so it supports random access, and if you need a lot of insertions and deletions, and you don't care about the immediate access, you should use list. when most insertions and deletions occur you can choose to deque this data structure at the head or tail of the sequence.

C + + STL summary one: Vertor and List

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.