Introduction STL (containers, iterators)

The full name of the standard template library STL (Standard Template Library), is a group that is rooted in a C ++ template library aimed at providing some basic container classes (container class) with efficient algorithms (algorithm) by the general procedure is to add algorithm data structure, with each other, work together, to complete the functions of the program. But this way they put data structures and algorithms tightly bound, can not be separated, the lack of flexibility

STL has five components: a container, iterators, algorithms, adapters, function objects.

Container (container) - used to store other objects iterator (iterator) - pointer like a conventional C language may be processed by the container object algorithm (algorithm) - algorithm for operation of the vessel through the iterator object adapter (adaptor) - using a base container object to be packaged, to change its interface to accommodate the needs of another function object (function object) - as an object STL lower order, to replace the traditional function pointer (function pointer)

Container divided into three categories:
  1. Sequential container
    vector: rear insert / delete, direct access to the
    deque: front / rear insert / delete, direct access to the
    list: a doubly linked list, anywhere insertion / deletion
    2) associated with the container
    set: set to quickly find no duplicate elements
    multiset : quickly find, may have duplicate elements
    map: one to one mapping, no duplicate elements, based on keyword search
    multimap: one to one mapping, there are duplicate elements, based on keyword search
    (Set / multiset map / multilmap achieve a balanced binary tree, insert, delete, retrieve, time complexity is O (long n))
    2 are collectively referred to as the front first type vessel
    3) A container adapter
    Stack the LIFO
    Queue: the FIFO
    The priority_queue: high priority first-out element
Total container member functions

All shared library containers member functions:
equivalent lexicographically two container size comparison operators: =, <, <=,>,> =, ==, =!
Empty: determining whether there is a container element
MAX_SIZE: multi-container can hold much element
size: the number of elements in the container
swap: exchange of two container contents
begin, end, insert, erase, etc.

vectorjie member function introduced

Here Insert Picture Description

vector Example
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> Array1D;   //构建一维数组
typedef vector<vector<int> > Array2D; //构建二维数组

int main(int argc, char *argv[])
{    
    int i,j;
    Array1D sz;
    for(i=0;i<10;i++)    //输入10个数
      sz.push_back(i);

    for(i=0;i<10;i++)
       cout<<sz[i]<<" ";  //vector继承了数组的[]获取元素的方法输出10个数 
    cout<<"\n"<<sz.front()<<"  "<<sz.back()<<endl;

    sz.erase(sz.begin()+3); //删除第四个数

    for(i=0;i<sz.size();i++)
      cout<<sz[i]<<" ";  //打印删除后剩余的数
    cout<<endl;

    sz.erase(sz.begin()+2,sz.begin()+5); //删除第三个数到第六个数 erase两个单数代表删除的区间

    for(i=0;i<sz.size();i++) 
     cout<<sz[i]<<" ";
     cout<<endl;

    sz.erase(sz.begin(),sz.end());//sz.clear();

    Array2D tw;

    tw.resize(5);  //定义一个5x5的动态二维数组  
    for(i=0;i<5;i++)
      tw[i].resize(5); 

    for(i=0;i<5;i++)
      for(j=0;j<5;j++)
        tw[i][j]=i*5+j;

    for(i=0;i<tw.size();i++)
    {
      for(j=0;j<tw[i].size();j++)  
        cout<<tw[i][j]<<" ";
      cout<<endl;
    }  
  
    system("PAUSE");  //press any key to continue......
    return 0;
}

operation result

0 1 2 3 4 5 6 7 8 9
0  9
0 1 2 4 5 6 7 8 9
0 1 6 7 8 9
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
请按任意键继续. . .
map example
#include <cstdlib>
#include <iostream>
#include <map>
#include <string>

using namespace std;

typedef map<string, int> Phone_Book;

void call(Phone_Book pb, string name)
{
    cout << "calling ... " << pb[name] << endl;
}

int main(int argc, char *argv[])
{
    map<string, int> phone_book;
    phone_book["zhangsan"] = 2901101;
    phone_book["LiSi"] = 2903105;
    
    call(phone_book, "LiSi");
    system("PAUSE");
    return EXIT_SUCCESS;
}

operation result

calling ... 2903105
请按任意键继续. . .
Iterator iterator

It's a lot of nature andC ++ / C pointer inIt is similar, or even a kind of pointers in C ++ compiler built-in iterators. It can be said that the pointer class; the software design of a basic principle, all the problems can be simplified by introducing a layer of indirection, this simplification is to use in the STL iterator done; iterator will be used in STL algorithms and containers linked, sticky and assume the role of agent; STL provides almost all of the algorithms are performed by the work accessors sequence iterator, each container defines its own proprietary iterator access to the container element
has two kinds of non-const and const.
It points to the element can be read by the iterator, which can modify the elements pointed to by the iterator non-const. Similar iterator usage and pointers.

Iterator class defines a container may be a method:

Container :: iterator class name variable name;
or:
a container class name :: const_iterator variable name;

To access an iterator pointing elements: * iterator variable

++ operations may be performed on the iterator to point to the next element in the container. If the iterator is an element reaches behind the rear of the container, the iterator becomes past-the-end value. Using an iterator a past-the-end value of the object to access is illegal, if NULL pointers or uninitialized as

STL iterators from weak to strong functionally divided into 5

1. Input: Input iterators provide read-only access to data.
2. Output: Output iterators provide the data write-only access.
3. Forward: Forward iterators provide read and write operations, and can be a time to move forward iterator.
4. Bidirectional: Bidirectional iterators provide read and write operations, one at a time and can be moved forward and backward.
5. Random Access: Random access iterators provide read and write operations, and can move in random data. A large number of iterators have a small number of iterations all functions can be used as a small number of iterations use

All iterators: ++ p, p ++
input iterators: * p, p = p1, p == p1, p = p1!
Output iterator: * p, p = p1
forward iterators: above all
bidirectional iterator is: above all, -p, p -,
random access iterators: all of the above, and: = i + p, p - = i,
p i +: returns a pointer to the back of the i-th element of p iterator
PI: returns p iterator pointing toward the front of the i-th element of
p [i]: i-th element of the latter referenced by p p <p1, p <= p1 , p> p1, p> = p1

container Iterator class
vector random
and random
list Two-way
lsetmultiset Two-way
map/multimap Two-way
stack Does not support iterators
queue Does not support iterators
priority_queue
Iterator examples
#include <iostream>
#include <vector>

using namespace std;
vector<int> myV;


int main(int argc, char *argv[])
{    
    for (int i=0;i<10;i++)
        myV.push_back(i);

    vector<int>::iterator it;
    for (it=myV.begin();it!=myV.end();it++)
        cout<<(*it)<<' ';

    system("PAUSE");  //press any key to continue......
    return 0;
}

operation result

0 1 2 3 4 5 6 7 8 9 请按任意键继续. . .
Introduction to Algorithms

STL can be provided in a variety of common containers algorithms, such as insert, delete, search, sort, and so on. About 70 kinds of standard algorithms.
Algorithm is a function of a template; algorithm to the container by the actuating element iterator. Many algorithm requires two parameters, a start element iterator is, one is a rear terminating element iterator element. For example, sorting and searching; some algorithm returns an iterator. For example find () algorithm, to find an element in the container, and returns a pointer to the iterator element; algorithm can handle containers can also be handled in the C language array

Classification algorithms

Changes in sequence algorithm copy, remove, fill, replace, random_shuffle, swap, ...... will change the container
non-changing sequence algorithm adjacent-find, equal, mismatch, find, count, search, count_if, for_each, search_n above function template is defined in
there are also other algorithms, such as the algorithm

Sorting and searching algorithms

Sort (template void sort (RanItfirst, RanItlast);
Examples

#include <algorithm>
#include <iostream>

using namespace std;
int tt[20];

int main(int argc, char *argv[])
{    
    int i;
    for(i=0;i<20;i++)
      tt[i]=20-i;
    sort(tt,tt+10);
    for(i=0;i<10;i++)
       cout<<tt[i]<<" ";

    system("PAUSE");  //press any key to continue......
    return 0;
}

operation result

11 12 13 14 15 16 17 18 19 20 请按任意键继续. . .
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
vector<int> gg;

bool sortspecial(int v1,int v2)
{
   return v1>v2;
}


int main(int argc, char *argv[])
{    
    int i;
    for(i=0;i<20;i++)
       gg.push_back(i);
    sort(gg.begin(),gg.end(),sortspecial);
    for(i=0;i<20;i++)
       cout<<gg[i]<<" ";
       
    system("PAUSE");  //press any key to continue......
    return 0;
}

operation result

19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 请按任意键继续. . .
find

template<class InIt, class T>
InItfind(InItfirst, InItlast, const T& val);

#include <algorithm>
#include <iostream>
using namespace std;


int main(int argc, char *argv[])
{    
    const int ARRAY_SIZE = 8 ;
    int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
    int *location ;   // stores the position of the first
                      // matching element.
    int i ;
    int value = 4 ;
    // print content of IntArray
    cout << "IntArray { " ;
    for(i = 0; i < ARRAY_SIZE; i++)
        cout << IntArray[i] << ", " ;
    cout << " }" << endl ;
    // Find the first element in the range [first, last + 1)
    // that matches value.
    location = find(IntArray, IntArray + ARRAY_SIZE, value) ;
    //print the matching element if any was found
    if (location != IntArray + ARRAY_SIZE)  // matching element found
        cout << "First element that matches " << value
             << " is at location " << location - IntArray << endl;
    else                                    // no matching element was
                                            // found
        cout << "The sequence does not contain any elements"
             << " with value " << value << endl ;
    system("PAUSE");
    return 0;

}

binary_search binary search requires containers have been ordered

template<class FwdIt, class T>
boolbinary_search(FwdItfirst, FwdItlast, const T& val)

Guess you like

Origin blog.csdn.net/qq_41767945/article/details/90314465