Viii. C + + Standard Template Library-stl overview

Source: Internet
Author: User

C + + Standard Template Library-stl overview first, the basic concept 1.1 Generic Programming

One of the core strengths of the C + + language is the ease of reuse of software, which is reflected in two ways:

    1. Object-oriented thinking: inheritance and polymorphism, Standard class library
    2. The idea of generic programming (Generic programming): template mechanism, and Standard Template Library STL

In short, it is a programming method that uses templates. Some commonly used data structures (such as linked lists, arrays, binary trees) and algorithms (such as sorting, lookup) as a template, then no matter what the data structure in the object, the algorithm for what kind of object, you do not have to re-implement the data structure, re-write the algorithm.

The Standard Template Library is a collection of templates for commonly used data structures and algorithms. With STL, you don't have to write most of the standard data structures and algorithms, and you get very high performance.

1.2 Basic Concepts in STL

container : A generic data structure that accommodates a wide variety of types, is a class template
iterators : Can be used to sequentially access elements in a container, similar to pointers
algorithm : A function template that is used to manipulate elements in a container

ii. Overview of containers

A container is a data structure that can be used to hold various types of data (basic types of variables, objects, etc.), and is a class template, divided into three types:

    1. Sequential container
      Vector, Deque,list
    2. Associative containers
      Set, Multiset, map, Multimap
    3. Container Adapter
      Stack, queue, priority_queue

When an object is inserted into a container, a copy of the object is inserted. Many algorithms, such as sort, lookup, require comparison of elements in a container, and some are ordered by themselves, so the classes that are placed in the container should often be overloaded with the = = and < operators.

2.1 Sequential Containers

A sequential container does not mean that the elements inside the container are ordered, and that the element's insertion position is independent of the element's value. There are three kinds of vector,deque,list.

vector refers to a dynamic array . Elements are stored continuously in memory. Random access to any element can be done in constant time, adding and removing elements at the tail end has better performance (in most cases, constant time). Header file is < vector>

deque refers to a two-way queue . Elements are stored continuously in memory. Random access to any element can be done in constant time (but second to vector). Adding and deleting elements at both ends has a better performance (in most cases, constant time).

list refers to a doubly linked list . Elements are not contiguous in memory. Adding and removing elements at any location can be done in constant time. Random access is not supported.

2.2 Associative containers

The associated container has several characteristics:

    1. The elements are sorted
    2. Inserts any element and determines its location by the appropriate collation
    3. Very good performance when looking for
    4. Usually implemented in a balanced binary tree, the time to insert and retrieve is O (log (N))

There are two categories:

    1. set/multiset(head file < set>)
      Set is the set. The same element is not allowed in set, and the same element is allowed in Multiset.

    2. map/multimap(head file < map>)
      The difference between map and set is that the elements stored in the map have only two member variables, one named first and the other named second, and map is ordered from small to large based on first value, and the elements can be retrieved quickly based on first.
      The difference between a map and a multimap is whether an element with the same first value is allowed

2.3 Container Adapter

There are 3 types of container adapters: Stack, queue, priority_queue.

Stack point Stack . is a finite sequence of items, and satisfies items that are deleted, retrieved, and modified in a sequence only the most recently inserted sequence (the item at the top of the stack). Last in, first out. Header file is < stack>

queue refers to queues . Inserts can only be done at the tail, delete, retrieve, and modify only allowed from the head. FIFO first. Header file is < queue>.

priority_queue refers to the priority queue . The highest priority element is always the first out-of-order. Header file is < queue>.

2.4 member functions

member functions in both sequential and associative containers:

begin 返回指向容器中第一个元素的迭代器end 返回指向容器中最后一个元素后面的位置的迭代器rbegin 返回指向容器中最后一个元素的迭代器rend 返回指向容器中第一个元素前面的位置的迭代器erase 从容器中删除一个或几个元素clear 从容器中删除所有元素front :返回容器中第一个元素的引用back : 返回容器中最后一个元素的引用push_back : 在容器末尾增加新元素pop_back : 删除容器末尾的元素erase :删除迭代器指向的元素(可能会使该迭代器失效),或删除一个区间,返回被删除元素后面的那个元素的迭代器
Three, iterators 3.1 Basic Concepts

Iterators are used to point to elements in sequential containers and associative containers, with similar usages and pointers, with const and non-const two types. An iterator allows you to read the element it points to, and it can also modify the element it points to by using a non-const iterator.

The method for defining an iterator for a container class can be:

Container class Name:: iterator variable name;
Container class Name:: Const_iterator variable name;

Access an iterator that points to an element:

* Iterator variable name

An iterator can perform a + + operation so that it points to the next element in the container. If the iterator reaches the end of the last element in the container and uses it at this point, it will be an error, similar to using null or uninitialized pointers.

3.2 Iterator Example
#include <vector>#include <iostream>using namespace STD;intMain () { vector<int>V//An array that holds an int element, with no element at firstV.push_back (1); V.push_back (2); V.push_back (3); V.push_back (4); vector<int>:: Const_iterator i;//Constant iterator     for(i = V.begin (); I! = V.end (); ++i)cout<< * I <<",";cout<< Endl; vector<int>:: Reverse_iterator R;//Reverse iterator     for(r = V.rbegin (); R! = V.rend (); r++)cout<< * R <<",";cout<< Endl; vector<int>:: Iterator J;///very-mass iterators     for(j = V.begin (); J! = V.end (); j + +) * j = -; for(i = V.begin (); I! = V.end (); i++)cout<< * I <<",";}

Output:

1,2,3,4,
4,3,2,1,
100,100,100,100,

3.3 Iterator Categories 3.3.1 Bidirectional iterator

If both P and P1 are bidirectional iterators, you can do the following with P, p1:

++P, P++ point P to the next element of the container--P, P-- make P point to the previous element in the container* P take the element that P points toP = P1 Assign ValueP == P1 , p!= P1 determine whether equal, unequal
3.3.2 Random Access iterator

If both P and P1 are random-access iterators, you can do the following with P, p1:

i 将p向后移动ii 将p向向前移动ii 值为: 指向 p 后面的第ii 值为: 指向 p 前面的第i个元素的迭代器p[i] 值为: p后面的第i个元素的引用p < p1, p <= p1, p > p1, p>= p1
3.3.3 containers and iterators
Container Container-corresponding iterator
Vector Random Access
Deque Random Access
List Bidirectional
Set/multiset Bidirectional
Map/multimap Bidirectional
Stack Iterators are not supported
Queue Iterators are not supported
Priotiry_queue Iterators are not supported
Iv. introduction of Algorithms 4.1 Basic Concepts

The algorithm is a function template, most of which are defined in < algorithm>.

STL provides algorithms that can be used in a variety of containers, such as find, sort, and other algorithms to manipulate elements in the container through iterators. Many algorithms can operate on a local interval in a container, so two parameters are required, one is an iterator to the starting element, and the other is an iterator that terminates the element behind it. For example, sorting and finding. Some algorithms return an iterator. For example, the Find () algorithm, finds an element in a container, and returns an iterator to that element.

The algorithm can handle the container, or it can handle ordinary arrays.

4.2 Algorithm Example
template<classclassconst T& val);

Both the first and last parameters are the container's iterators, which give the lookup interval start and end point in the container [First,last]. The starting point of the interval is in the lookup range, and the end point is not. Find elements that are equal to Val in [First,last] are judged equal with the = = operator.

The function return value is an iterator. If found, the iterator points to the element that was found. If it is not found, the iterator is equal to last.

v. The concept of "big", "small" and "equal" in STL 5.1 Basic Concepts

The elements inside the associative container are sorted from small to large

    1. Some algorithms require the range of operations to be ordered from small to large, called "Ordered interval algorithm"
      Example: Binary_search
    2. Some algorithms sort the interval from small to large, called the "Sorting algorithm"
      Example: Sort
    3. There are other algorithms that use the concept of "big", "small"

When using STL, the following three statements are equivalent in the default case:

    1. X is smaller than y
    2. Expression "x < Y" is true
    3. Y is larger than x

About "equality":

    1. Sometimes "x and Y equals" is equivalent to "x==y is true"
      Example: An algorithm that is performed on an unordered interval, such as a sequential lookup find
      ......
    2. Sometimes "x and Y equals" is equivalent to "x is less than Y and y is less than x and false"
      Cases:
      Ordered interval algorithms, such as Binary_search
      member function of the association container itself find
      ......
5.2 Program Examples
#include <vector>#include <algorithm>using namespace STD;classa{intV PublicAintV): V (v) {}BOOL operator< (ConstA &a)Const{cout<<v<<"<"<<a.v<<"?"<<endl;return false; }BOOL operator==(ConstA &a)Const{cout<<v<<"=="<<a.v<<"?"<<endl;returnV==A.V; }};intMain () {//overloaded operator < binary lookupA a[] = {A (1), A (2), A (3), A (4), A (5)};cout<<binary_search (A, A +5A9));return 0;}

Output:

3<9?
2<9?
1<9?
9<1?
1

Binary find, finally found 1 No more can be looked up. Compare whether 9 is less than 1, the result is false, compare 1 is less than 9, the result is false, this time think 9==1, Output 1.

Vi. Summary
    1. Three basic concepts of STL: containers, iterators, algorithms
    2. Containers are divided into sequential containers, associative containers, container adapters
    3. Sequential containers are divided into vectors (dynamic arrays), deque (bidirectional queues), list (doubly linked list)
    4. Associative containers are divided into Set/multiset, Map/multimap
    5. Container adapter stack, queue, priority_queue
    6. Iterators are divided into bidirectional iterators, random-access iterators, different types of iterators that can be used by different containers
    7. The algorithm is a function template, most of which are defined in < algorithm>
    8. The concepts of "big", "small" and "equal" in STL can be defined by themselves, and may differ from those in conventional sense.

Viii. C + + Standard Template Library-stl overview

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.