STL Usage Summary

Source: Internet
Author: User
Tags abstract bool data structures define function
1.     Overview The idea of generic programming is based on the assertion that the partial algorithm proposed by A.stepanov can be independent of the data structure. The early 1990s A.stepanov and Meng Lee wrote STL in C + + in accordance with the theory of generic programming. Until 1998, however, STL became the official standard for C + +. In the later years, the major mainstream compilers have also been added to the STL support, so that STL began to be widely used. STL embodies the core idea of generic programming: independent data structures and algorithms (this is a programming philosophy independent of OO). STL mainly consists of several core components, namely iterators, containers, algorithms, function objects, adapters. The object of the container; an iterator is an abstraction of the access logic of a container, a connection between an algorithm and a container; an iterator that implements the independence of the container and the algorithm by adding an indirect layer; A function object, which is the overloaded operator () operator. ; An adapter is a new data structure implemented by combining a particular container. In the following sections, we will describe the basic application of several core components in detail. 2.     Basic C + + generation of historical background gives C + + too much responsibility, such as compatible with C, integrated programming language, although these give the C + + powerful features, but also thrown to a great degree of complexity. In this article, we are not going to take you into the complex areas of C + +, but you need to have a certain C + + base, such as classes, structs, and so on. STL is deeply rooted in C + + infrastructure, which includes inline, function objects, function templates, class templates, and so on. 2.1.  Inline is a special language mechanism in C + + that is identified by using inline. C + + When compiling inline-identified functions, the code of the inline function is inserted directly into the call location of the inline function according to the specific rules, which can improve the efficiency of the program, but it also causes the code to expand to some extent. Take a look at the following example: inline global function inline void max{...}; Inline member function Class a{public:          inline void max{...};} The 2.2.  Function Object function object is the object that overloads the operator () operator. Relative function pointers, function objects can have states, are more secure, more flexible, and have no additional overhead. In STL, a function object is often used as an input parameter to an algorithm or as an instantiated parameter of a container.。 Consider the following example: Defining a Function object class classs lessthan{public:          lessthan (int val): M_val ( val) {}          bool operator () (int val) {return M_val < val;} private:          int m_val; }; Defines a function object LessThan less (5); Call the Define function object less (10);//Return to True 2.3.  template in C + + is the technical basis for STL implementations. Templates in C + + can be categorized as function templates and class templates. Function templates Abstract operations that are of the same nature for different types. such as the max operation for Int/long/string. Consider the following example: Define an operation that takes two types of values or the maximum value of an object Template<typename t> t max (T a,t b) {return a>b? A:b;} takes the maximum value of two int max (0,10);//Return Back to 10 to fetch the maximum value of two string objects max (String ("Hello"), String ("World"));//Return String ("World") the template in C + + of the 2.4.  class template is the technical basis of the STL implementation. Templates in C + + can be categorized as function templates and class templates. Class templates Abstract the same kind of transactions for different types. such as the stack for int/long/string. Take a look at the following example: Define a generic stack Template<typename t> class stack{public:           inline void push (const t& value) {...}          T pop () {...} void clear () { ...} BOOL Empty () const{...} }; Declares a Stack of type int typdef stack<int> intstack; Declares a string of type Stack typdef stack<string> intstack; Iterators in the 3.     iterator are a generalization of C + + pointers, which act as a middle tier between the algorithm and the container, providing a consistent way to handle different data structures. Iterators can also be seen as a constraint on the access to a container's data structure. Iterators in STL can be categorized into classes: Random access iterators (random-access-iterator), bidirectional access iterators (Bidirectional-access-iterator), forward iterators (forward iterator), Input iterator (input-iterator), output iterator (output-iterator). The inheritance between them is shown below:  input-iterator  output-iteartor       forward-iterator:o utput-iteartor , input-iterator  Bidirectional-access-iterator:forward-iterator Random-access-iterator:bidirectional-access-iterator   iterator diagram 3.1.  an input iterator input iterator can also be referred to as a forward-only read-only accessor. First it provides read-only access to the container, and secondly it can only forward iterations in the container (that is, only the + + operation is provided). All container iterators have the characteristics of an input iterator. There are three things you can do with an input iterator: 1.         v = *x++ 2.          v = *x,x++ 3.         v = *X,++X Note: V is a value, X is an iterator 3.2.  output iterator output iteratorIt can also be referred to as a forward-only write-accessor, first it provides write-only access to the container, and second, it can only forward iterations in the container (that is, only the + + operation is provided). With the output iterator you can do the following three things: 1.         *x++ = V 2.          *x = V, x + + 3.         *x = V, ++X Note: V is a value, X is an iterator-3.3.  forward iterator that inherits from the input and output iterators, thus having all the characteristics of the input and output iterators, providing read-write access to the container's data structures but also the ability to only forward iterations (that is, only the + + operation is provided). Therefore, you can operate on the forward iterator: R = = S/++r = = ++s. Consider the following example: Define an algorithm for linear lookups using a forward iterator template<typename forwarditerator,typename t> forwarditerator linear_search ( ForwardIterator first,forwarditerator last,const t& value) {         for (; First! = last; ++first) {                   if (*first = = value)                              return first; } return last; } Test int ia[] = {35,3,23}; Vector<int> VEC (ia,ia+3); Vector<int>::iterator it = Linear_search (Vec.begin (), Vec.end (), 100); if (It! = Vec.end ()) std::cout << "Found" << Endl; else std::cout << "not Found" << Endl;            test Result: not Found 3.4.  bidirectional access iterator bidirectional access iterator inherits from the former to the iterator. Thus having all the characteristics of a forward iterator, a bidirectional access iterator also has a back-access capability (that is, providing only-operation). Consider the following example: Define a sort algorithm that leverages the bidirectional iterator template<typename bidirectionaliterator,typename compare> void Sort_me ( Bidirectionaliterator first,bidirectionaliterator last,compare Comp) {    for (Bidirectionaliterator i = First; I! = Last; ++i)     {        Bidirectionaliterator _last = last;   & nbsp;     while (i! = _last--)         {             if (comp (*i,*_last))                  Iter_swap (i,_last);        }    }} Test int ia[] = {123,343,12,100,343,5,5}; Vector<int> VEC (ia,ia+7); Sort_me (Vec.begin (), Vec.end (),less<int> ()); Copy (Vec.begin (), Vec.end (),ostream_iterator<int> (cout, "")); Std::cout << Endl;           Test Result: 5 5 123 343 343 3.5.  random Access iterator A random access iterator inherits from a bidirectional access iterator and thus has all the characteristics of a bidirectional access iterator. The difference is that with random access iterators you can have random accesses to the container data structure, so a random access iterator can also define the following actions: 1.          operator+ (int) 2.         operator+= (int) 3.          operator-(int) 4.          operator-= (int) 5.         operator[] (int) 6.          operator-(Random-access-iterator) 7.&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;   operator> (Random-access-iterator) 8.          operator< (Random-access-iterator) 9.         operator> = (random-access-iterator) 10.     operator<= (Random-access-iterator) in the STL, Random Access bidirectional iterators can only be used in sequential containers. Take a look at the following example:           test output vector data     int ia[] = { 123,343,12,100,343,5,5};     vector<int> VEC (ia,ia+7);     for (int i = 0; i < vec.size (); ++i)         std::cout << ve C[i] << "";                      Test results are: 123 343 343 5 5 4.     container container is where the object. Container is one of the core parts of STL, it is the attachment of the iterator and the target of the algorithm. The containers in the STL can be divided into sequential containers (Sequence Container) and associative containers (associative Container). The container adapter (Container Adaptor) is a sequential container (Sequence Container) or an associative container(associative Container) a container that is more binding (or more powerful) for packaging. The following table lists the main (standard and non-standard) containers in the STL:
order container (Sequence Container) container remarks
Vector  
Stack non-STL standard, Vector adapter (Adaptor)
list  
slist non-STL standard, List adapter (Adaptor)
deque  

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.