Standard Template Library

Source: Internet
Author: User
Tags map class

    • Overview

Standard Template Library STL includes container, iterator, algorithm ;

A container is a data structure that contains data, and the container contains objects that are elements;

An iterator is an object that is used to access an element in a container, which is a pointer to an element object;

The algorithm refers to some standard algorithms which can be used in various containers, such as sorting, inserting, etc.

The algorithm uses iterators to operate on the container.




    • Iterators

an iterator is an abstraction of a pointer, which is a generalized pointer (generic pointer);

Iterators in the standard library are defined as class templates, allowing for uniform behavior on different data structures, that is, traversing the elements in the container in the same way, without caring whether the underlying data structure is a vector stored sequentially or a list of chained stores.

The iterators defined in the standard library are divided into V, and different categories of iterators have different functions, providing different operations, as shown in the following table:


The meaning of an iterator operation is basically similar to the corresponding action of a pointer type.

Second,

The iteration types defined in different container types defined in the standard library belong to different iterator categories:

1 The iterator of the vector container and the deque container is a random access iterator;

2 The iterator of the list container is a bidirectional iterator;

3 iterators of all associative containers are bidirectional iterators;

4 The container adapter does not support iterators;




    • Container

The container in STL is divided into: sequential container, associative container, container adapter;

The elements in the sequential container are stored in the relative position of the elements in the container, and are accessed through the position sequence;

Key ordering of the elements in the associative container;

A container adapter enables a container to work in a different abstract type;

Note: The C + + rule: The type that the container element belongs to must support copy and assignment operations, the reference type does not support assignment operations, therefore cannot be used as a container element type, the I/O library type does not support assignment and copy operations, and therefore cannot be used as a container element type.

first, the sequential container

The standard library defines three sequential container classes, such as the following table:


1 definition and initialization of container objects

1.1 The Container class is a template class, so you need to include the relevant header file before you define the container object, and then instantiate the corresponding class template;

Vector<int> iv;//defines vector object IV for storing int elements list<double> dl;deque<string> SD;

1.2 The Sequential container class also provides some additional constructors, such as the following table:


Description

A c is the name of the container class template (such as list), T is the type of the element in the container, and C is the container object that is created;

b The first three constructors apply to all containers, and the latter two only apply to sequential containers;

C- value initialization refers to the initialization of elements that are automatically generated by the standard library when no initial value is specified, and when the element type is a built-in type, the standard library uses 0 values as the initial value of the element, and the element type is the class type. The standard library initializes the element with the default constructor of the class;

(Note: If the element type is a class type and the class has a custom constructor but no default constructor, you cannot use the last constructor listed in the previous table to create the container object)

Example:

Assigns the specified number of elements, initializes the values of these elements vector<int> Iv1 (10); The IV1 contains 10 elements of the 0-value element//assigns the specified number of items, initializes the elements to the specified value vector<int> iv2 (10,1); IV2 contains 10 1 value elements//initializes the vector object to a copy of the element int ia[]={0,1,2,3,4,5,6,7,8,9};vector<int> iv3 (ia,ia+10); Iv3 contains 10 elements with a value of 0~9

Note: When using an iterator parameter , the container type can be different, and the type of the element in the container is only compatible.


2 type aliases defined in the container

For ease of definition and use, the container type in the standard library provides type aliases;

The definition of a type alias is generally related to the element type in the container, which is used to declare variables, parameter parameters of member functions, return values of member functions, and so on in a container class.


When you use a type alias defined in a container class, you need to include the container class name qualification before the alias;

If the type alias iterator defined in the vector container that holds the int element, it should be represented as vector<int>::iterator.


3 accessing elements

There are two ways to access elements in a container: Using the access operations provided by the container class, and through the container's iterators.

3.1 element access operations for sequential containers


Example:

#include <iostream> #include <vector>using namespace Std;int main () {int Ia[]={0,1,2,3,4,5,6,7,8,9};vector <int> IV (IA,IA+10); Iv.front () =10;iv[1]=11;iv.at (2) =12;iv.back () =19;cout<< "The first element:" << iv[0]<<endl;cout<< "The second element:" <<iv.at (1) <<endl;cout<< "The third element:" <<iv[2]<<endl;cout<< "The last element:" <<iv.at (9) <<endl; System ("pause"); return 0;}

Execution Result:

The first element:10

The second element:11

The third Element:12

The last element:19


3.2 Accessing container elements through container iterators


Example:

#include <iostream> #include <vector>using namespace Std;int main () {vector<int> IV (10,2);// Creates a vector container with 10 elements with a value of 2 Vector<int>::iterator it;//declares an iterator object Vector<int>::reverse_iterator rit;// Declares a reverse iterator object It=iv.begin ();//it points to the first element *it+=10;rit=iv.rend ();//RIT points to the previous position of the first element *rit+=10;//adds the value of the first element 10it=iv.end ();// It points to the next position of the last element * (it-1) =100;//changes the value of the last element to 100rit=iv.rbrgin ();//RIT points to the last element *rit-=20;//the last element value minus 20for (it=iv.begin (); It!=iv.end (); it++) cout<<*it<< ""; System ("pause"); return 0;}

Execution Result:

22 2 2 2 2 2 2 2 2 80


4 adding elements

Once a container object is created, it should be allowed to add elements to it;


Description: C represents the container object, and the vector container does not provide push_front operations.

Example:

#include <iostream> #include <vector> #include <deque> #include <string>using namespace Std;int Main () {vector<int> iv;deque<string> sd;int ia[]={100,100,100};for (int i=1;i<11;i++) {//Add 10 elements at the end of the terminal 1~ 10iv.push_back (i);} Iv.insert (Iv.begin (), 20);//Add an element Iv.insert (Iv.begin () +4,2,30) to the head end of the vector container, or two elements after the fourth element of the vector container Iv.insert ( Iv.end (), ia,ia+3);//Add the first three elements of the array ia to the end of the vector container Sd.push_back ("is"), Sd.push_front ("the"), Sd.insert (Sd.end (), "an"); Sd.insert (Sd.end (), "example"); for (Vector<int>::iterator It=iv.begin (); It!=iv.end (); it++) cout<<*it << ""; Cout<<endl;for (Deque<string>::iterator it=sd.begin (); It!=sd.end (); it++) cout<<*it << "";cout<<endl; System ("pause"); return 0;}

Execution Result:

20 1 2 3 30 30 4 5 6 7 8 9 10 100 100 100

This was an example

Added: container type and operational efficiency

The vector container is based on an array, and its elements are stored continuously in memory, so the random access of the elements is very efficient; colleagues because the elements are stored continuously, the vector container, in addition to the end of the container, when inserting or deleting elements at any other location, needs to move all the elements behind the element, which is less efficient;

The list container is implemented with a doubly linked list structure whose elements are not contiguous, so you do not need to move other elements when inserting and deleting elements, just modify the list pointers. Therefore, the list container is efficient in inserting and deleting anywhere, and because the element is not contiguous, the list container does not support fast random access, and it is less efficient to access a particular element that requires a positive or reverse traversal of the other elements involved;

The Deque container is based on an array, but with more complex data structures, inserting and deleting elements at both ends of the container is highly efficient, but inserting or deleting in the middle of the container is not as efficient as the list container, because the Deque container is based on an array implementation, and it is more efficient to randomly access the elements at once.

In the process of container programming, different types of containers should be selected according to the application characteristics, and the execution speed of the program should be improved.


5 Deleting an element

For containers that have already been created and contain elements, it is allowed to delete them.


Example:

<pre name= "code" class= "CPP" > #include <iostream> #include <deque>using namespace Std;int main () {int ia[]={1,2,3,4,5,6,7,8,9,10};d eque<int> ID (ia,ia+10);d eque<int>::iterator it;for (It=id.begin (); it!= Id.end (); it++) cout<<*it<< ""; Id.pop_front (); Id.pop_back (); for (It=id.begin (); It!=id.end (); it++) cout <<*it<< ""; It=id.begin (); Id.erase (Id.erase (it+1));//delete second to third element for (It=id.begin (); It!=id.end (); it++) cout<<*it<< ""; Id.erase (Id.begin (), Id.begin () +3);//delete the first three elements for (It=id.begin (); It!=id.end (); it++) cout <<*it<< ""; Id.clear (); if (Id.empty ()) cout<< "No element in double-ended queue" <<endl; System ("pause"); return 0;}

Note: Not all container iterators support + operations, such as the list container;


6 Comparison of containers

Each container supports comparison operations, which compare operations using relational operators: = = = = < <= > >=;

Two container objects can be compared on the premise that the container type is the same, the elements in the container are of the same type;

If the element type of the container does not support a relational operator, such a container cannot be compared accordingly;



7 operations on container size

Container size refers to the number of elements currently stored in the container;



8 Assignment and exchange of containers

The assignment of the container and the Exchange Act on the whole container;


Note: Theswap operation does not delete and insert elements, only the names of the two containers are exchanged;

Some container operations can have an effect on the number or position of elements, which may invalidate some iterators in the container, so do not store and reuse iterators returned by operations such as begin, end, and so on, each time you need these iterators to take advantage of the relevant actions.


second, the related container

Instead of storing and accessing elements through positional order, associative containers Store and access elements through key keys;

The associated container supports most operations, including: the first three constructors, all container operations that get iterators, insert operations, clear and erase operations, relational operations, operations on container size (except resize operations), assignment and Exchange operations (except assign operations);

Four associative containers are available in the standard library:


1 Pair Type

The pair type is used as the element type in the map and Multimap container classes, and is a template class that is defined in the header file utility;

A pair object contains two data members: first and second, the two members are public members, so they can be accessed directly from the pair object.

To create an action on a pair object:


Comparison operation for pair objects:



2 Map Container

A map container is a set of key-value pairs, often referred to as associative arrays, where the "association" refers to the relationship between the value of the element and the key through the key to access the value;

Definition and initialization of 2.1 map object

The Map container class provides three constructors:

2.2 Type aliases defined in the Map class

In addition to the type aliases defined in the Sequential container class, the map class defines the type aliases:


Attention:

The Value_type in the map class is the pair type, whose first member is the const type, i.e. the key of the element in the map container cannot be modified;

To modify the key of an element in a container, you can only use indirection: first delete the element, then insert a new element, and the new element's key is set to the desired key;

2.3 Accessing elements in the map container

Use an element subscript or an iterator to an element to access the elements in the map container;

When using subscript, be aware of the following:

The element subscript of a container can be an integer or another type (such as a string);

b when using subscript to access an element, the value in the element is returned if the element exists, and if the specified element does not exist, it will result in a new element being added to the container, where the value of "key" is the given subscript value, and the value of the element is initialized with the value;

The return value type of the C map container subscript operation is the Mapped_type type defined in the map container, and the return value type of the container's iterator is the Value_type type defined in the container;

2.4 Adding elements to the map container

Use the insert Operation or use the subscript to get the element, and then assign a value to the value of the acquired element;

Where the map container provides insert operations:


Note: The map container does not provide push_back and push_front operations, and if the key for the inserted element already exists in the container, insert will not do anything;

2.5 Finding elements in the map container

The subscript operation of the map container has side effects: if the element corresponding to the specified key (subscript) does not exist in the map container, the subscript operation causes the new element to be inserted in the map container;

To check if a key exists in the map container and you do not want to insert the element, you can use the Find and count operations:


2.6 Deleting elements from the map container

To delete an element from the map container using the erase operation:



3 Multimap Container

The multimap container is similar to the map container, except that the keys in the Multimap container can be duplicated, that is, multiple elements can contain the same key;

Because a key in the Multimap container may be associated with more than one value, the Multimap class does not support subscript operations;

The following is a list of multimap operations that differ from map operations:

The insert operation adds a new element each time it is called (in the Multimap container, the same key element is stored adjacent);

A erase operation with a key value parameter deletes all the elements associated with the key and returns the number of deleted elements;

The count operation returns the number of occurrences of the specified key;

The iterator returned by the find operation points to the first element associated with the lookup key;

Gets the action of the element iterator associated with the specified key:



4 Set Container

The set container is used for the collection, and the elements in the set are not duplicated; theelement of the set container is the key itself, that is, only the key;

The operations supported by the map container, which are basically supported by the set container, have only the following differences:

The set container does not support subscript operation;

The Mapped_type type is not defined in the Set container class;

The value_type type defined in the Set container is not the pair type, but is the same as the Key_type, which refers to the type of the elements in the set;


5 multiset Container

The Multiset container is similar to the set container, except that the keys in the Multiset container can be duplicated, that is, the duplicate elements can be stored;




three, the container adapter

The so-called "adapter" refers to a mechanism that makes the behavior of something similar to the behavior of another thing;

Three types of container adapters are available in the standard library:


Omitted...


Standard Template Library

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.