PKU C + + program Design Internship study Note 6 Standard Template Library STL

Source: Internet
Author: User

Standard Template Library STL

8.1 STL Overview 1. Generic Programming

One of the core strengths of the C + + language is ease of software reuse

There are two aspects of the reuse in C + +: 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.

Basic Concepts in 2.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. The algorithms themselves are independent of the type of data they manipulate, so they can be used on any data structure from simple arrays to highly complex containers.

int array[100]; the array is the container, and the int * Type pointer variable can be used as an iterator, and the sort algorithm can be applied to the container, sorting it: sort (array,array+70); Sort the first 70 elements    array and array+70 are iterators
3. Container overview

Data structures that can be used to hold various types of data (basic types of variables, objects, etc.) are class templates , divided into three types:

    • Sequential container
      Vector,deque bidirectional queue, List doubly linked list
    • Associative containers
      Set,multiset,map,multimap
    • Container Adapter
      Stack,queue,priority_queue
When an object is inserted into a container, the object is inserted in aReproductions。 Many algorithms, such as sort, lookup, require comparison of elements in a container, and some are ordered by themselves, so that the class into which the objects belong to the container should oftenoverloading = = and < operators。

4. Introduction to Sequential containers

The container is not ordered, and the insertion position of the element is independent of the value of the element.

There are three kinds of vector,deque,list

Vector Header Files <vector>

    • 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). But when the storage space is not enough, need to open up new space, the original elements are copied and then inserted, time complexity is O (n).
    • The time complexity of inserting or deleting elements in the head or Middle is O (n) because the element needs to be moved.
Deque header File <deque>
    • Two-way queue. Elements are stored continuously in memory.
    • Random access to any element can be done in constant time (but second to vector).
      The reason for the second vector is that it is a two-way queue, where the element address needs to be judged if it exceeds the end and then minus the length.
    • Adding and deleting elements at both ends has a better performance (in most cases, constant time).
List header Files <list>
    • 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.
5. Introduction to associative containers
    • The elements are sorted
    • Inserts any element and determines its location by the appropriate collation
    • Very good performance when looking for. usually implemented in a balanced binary tree, the time to insert and retrieve is O (log (N))
    • Set/multiset header File <set>
      Set is the set. The same element is not allowed in set, and the same element is allowed in Multiset.
    • Map/multimap header 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 map and Multimap is whether the element with the same first value is allowed.
6. Introduction to Container Adapters
    • Stack
      Stack.   Last in, first out. Header Files <stack>
    • Queue
      Queue.    FIFO first. Header Files <queue>
    • Priority_queue
      Priority queue.    The element with the highest priority is always at the head of the team. Header Files <queue>
7. member functions in both sequential and associative containers
    • Begin returns an iterator that points to the first element in the container
    • End returns an iterator that points to the position after the last element in the container
    • Rbegin returns an iterator that points to the last element in the container
    • Rend returns an iterator that points to the position in front of the first element in a container
    • Erase remove one or several elements from a container
    • Clear removes all elements from the container
8. Common member functions for sequential containers
    • Front: Returns a reference to the first element in the container
    • Back: Returns a reference to the last element in the container
    • Push_back: Add a new element at the end of the container
    • Pop_back: Delete the element at the end of the container
    • Erase: Removes the element that the iterator points to (which may invalidate the iterator), or removes an iterator that returns the element that is behind the deleted element
9. iterators

    • Used to point to an element in a sequential container and an associative container
    • Iterator usages and pointers are similar
    • There are two types of const and non-const
    • An iterator allows you to read the element it points to
    • You can also modify the element to which it points by using a non-const iterator
The method for defining an iterator for a container class can be:
Container class Name:: iterator variable name;
Or:
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.

There are two common iterators: bidirectional iterators and random-access iterators.

10. Bidirectional iterators if both P and P1 are bidirectional iterators, you can do the following with P, p1:
    • ++p, p++ causes p to point to the next element in the container
    • --p, p--causes p to point to the previous element in the container
    • * P takes the element that P points to
    • p = P1 Assignment
    • p = = P1, p!= p1 to determine whether equal, unequal
11. Random-Access iterators if both P and P1 are random-access iterators, you can do the following for P, p1:
    • All operations for bidirectional iterators
    • p + = I move p backward to I element
    • P-= I moves P forward to the I element
    • The P + I value is: an iterator that points to the I element after P
    • The P-i value is: an iterator that points to the I element in front of P
    • P[i] Value: A reference to the I element after P
    • P < P1, P <= p1, p > P1, p>= p1
8.2 STL Overview Cont. 1. iterators on the container

Iterator category on container container
Vector Random Access
Deque Random Access
List bidirectional
Set/multiset bidirectional
Map/multimap bidirectional
Stack does not support iterators
Queue does not support iterators
Priority_queue does not support iterators

Some algorithms, such as Sort,binary_search, need to access the elements in the container through a random-access iterator, then the list and the associated container do not support the algorithm!

The list iterator is a bidirectional iterator that correctly iterates through the list of methods:list<int> V;list<int>::const_iterator ii;for (ii = V.begin (); ii = V.end (); + + II)  cout << * II;       Use the Dereference method to take the element.  The loop's judging condition is! = Wrong practice: for (ii = V.begin (); II < V.end (); II + +)  cout << * ii;//bidirectional iterator does not support <,list no [] member function for (int i = 0;i < V.size (); i + +)  cout << v[i];
As you can see, the iterator to the list is a bidirectional iterator that does not support the < operation and does not have a [] member function.

2. Introduction to Algorithms
    • 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, etc.
    • The algorithm manipulates the 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. Like the Find () algorithm, finds an element in the container and returns an iterator to that element
    • The algorithm can handle the container, or it can handle the normal array
3. Algorithm example: Find () Declaration: (Different compilers may not be the same, this gives the declaration in Dev C + +)
Template<class init, class T>init find (init First, init last, const 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 in [First,last) finds an element equal to Val
    • Use the = = operator to determine equality
    • 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 the last
#include <vector> #include <algorithm> #include <iostream>using namespace Std;int main () {//find algorithm example C0/>int array[10] = {10,20,30,40};  Vector<int> v;  V.push_back (1); V.push_back (2);  V.push_back (3); V.push_back (4);  Vector<int>::iterator p;  p = Find (V.begin (), V.end (), 3);  if (P! = v.end ())    cout << * p << endl;//Output 3  p = Find (V.begin (), V.end (), 9);  if (p = = V.end ())    cout << "not found" << Endl;  p = Find (V.begin () +1,v.end () -2,1); Entire container: [1,2,3,4], look for interval: [2,3]  if (P! = v.end ())     //not found, p is v.end ()-2, point to 3    cout << * p << endl;< C15/>int * pp = find (array,array+4,20);//array name is iterator  cout << * pp << Endl;} Output: 3not found320
The concept of "big" and "small" in 4.STL

    • The elements inside the associative container are sorted from small to large
    • Some algorithms require the range of operations to be ordered from small to large , called " ordered interval algorithm "
      Example: Binary_search
    • Some algorithms sort the interval from small to large , called the " sorting algorithm "
      Example: Sort
    • There are other algorithms that use the concept of "big", "small"
    • when using STL, the default case, the following three statements are equivalent :
      1) x is smaller than y
      2) expression "x<y" is true
      3) y is larger than x
The concept of "equality" in 5.STL
    • Sometimes "x and Y equals" is equivalent to "x==y is true"
      Example: An algorithm that is performed on an unordered interval, such as finding find in order ...
    • Sometimes "x and Y equals" is equivalent to "x is less than Y and y is less than x and false"
      Example: An ordered interval algorithm, such as Binary_search,
      The member function of the association container itself find ... (Associative container is used to find, itself with member function find, you can not use the Find algorithm or other Binary_search algorithm to find the association container)
6.STL "Equality" concept Demo
#include <iostream> #include <algorithm>using namespace std;class A {  int v;  Public:    A (int n): V (n) {}    bool operator< (const A & A2) const    {      cout << v << "<" &L t;< a2.v << "?" << Endl;      return false;    }    BOOL operator = = (Const A & A2) const    {      cout << v << "= =" << a2.v << "?" << Endl ;      return v = = A2.V;    }}; int main () {  a A [] = {A (1), A (2), A (3), a (4), A (5)};  cout << Binary_search (a,a+4,a (9)); Binary find  return 0;} Output result: 3<9?2<9?1<9?9<1? 1
As you can see here, Binary_search calls the < operator and does not use the = = operator. The equivalent concept in the lookup is that "x is less than Y and y is less than x and false"


PKU C + + program Design Internship study Note 6 Standard Template Library STL

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.