stl--adapter, common algorithm use

Source: Internet
Author: User
Tags prototype definition

To learn STL, it is necessary to use the adapter and some common algorithms. They are all important components of the STL.

Adapter

In the STL, adapters can be fitted with some containers. For example, the stack and queue are deque by a double-ended queue. In fact, the adapter is also a design pattern , which is to convert the interface of a class into another interface that the user wants. Simply put: What is needed is right in front of you, but it is not convenient to use or be used, and for a short time it cannot be modified, so we can adapt it by existing things.

There are three types of adapters in the STL:

① is a container adapter that is applied to a container, such as a stack and a queue is a deque interface ② an iterator adapter applied to an iterator, such as a reverse iterator that is the interface of an iterator ③ applied to the function adapter of the functor.

But we usually use the container adapter more, so we focus on the use of container adapter, other adapters can refer to the STL source analysis.

(1) Stack/queue

We all know that stack and queue are special linear data structures that require the insertion and removal of data at their fixed end
For In the STL container,deque is a double-open structure, so the STL as the stack and the bottom of the queue structure, and then the deque slightly modified to implement the stack and queue.

Like this: a new structure that is implemented by repackaging the interface of a class, called an adapter

As the stack prototype defines :

Common interfaces:

The queue prototype definition resembles the following:

Note: Stack queue does not have iterators

(2) Priority_queue

The priority_queue (priority queue) is a weight-critical queue that allows the user to insert elements into a container in any order, but takes the highest (low) priority element each time it is taken, which is exactly what the heap has, so the precedence _queue takes the vector as the underlying storage element space , wraps the heap algorithm, and realizes the priority queue.

Defining Prototypes:

Note: Its header file is included in # include <queue>

With regard to its use:

1. The Priority_queue Priority queue container also does not provide iterators for direct access to elements at any other location, because only the first and the tail elements of the team are taken into action.

2. When you call the top member function to take the team head element, the resulting element is the most weighted element because of the heap algorithm encapsulated inside the queue.

3. When a pop is called to delete the top element, the deleted element is the element with the highest weight. And usually the member top is called before the pop is retrieved.

The POP member function effectively calls the POP_HEAP algorithm to preserve the Priority_queues heap property, and then calls the member function of the underlying container object Pop_back to delete the element.

4. It also supports customizing the comparison of the pseudo functions for custom order comparisons.

Combining these operations, we can implement a small function .

  case: Based on the number of occurrences, the statistical pre-K programming language

 Vector<string> gettopklanguage (const vector<string>& v, int k) {unordered_map<string, int> uma     P     Statistics of each language count for (int i=0; i< v.size (); ++i) {umap[v[i]]++;     } umapite it1 = Umap.begin ();         while (it1! = Umap.end ()) {cout<<it1->first<< ":" <<it1->second<<endl;     ++it1;  }//With Priority_queue to Pair<string, int> by weighted value priority_queue<string, Vector<umapite>, CountCompare>     Pq     Umapite it = Umap.begin ();     int m = k;         while (it = Umap.end ()) {if (M > 0 && m--) pq.push (IT);             else {//takes the element with the highest weight (lowest value) in the current queue to pop, which is equivalent to gradually popping up the language with fewer occurrences, leaving more occurrences.             Umapite top = Pq.top ();                 if (It->second > Top->second) {pq.pop ();               Pq.push (IT);     }} ++it;     } cout<<endl; while (!pq.empty ())     {cout<<pq.top ()->first<< ":" <<pq.top ()->second<<endl;     Pq.pop (); }//vector<string> ret; for (int i=0; i<k; ++i)//{//Ret.push_back (Pq.top ()->first);//Pq.pop ();//}//return RET;     } int main () {vector<string> V;     V.push_back ("PHP");     V.push_back ("Python");     V.push_back ("Python");     V.push_back ("Java");     V.push_back ("PHP");     V.push_back ("C + +");     V.push_back ("C + +");     V.push_back ("C + +");     V.push_back ("PHP");     V.push_back ("Java");     V.push_back ("PHP");     V.push_back ("Go");     V.push_back ("PHP");     V.push_back ("Java");     V.push_back ("PHP");     V.push_back ("PHP");      V.push_back ("PHP");      Gettopklanguage (V, 3); return 0; }

Here to count the first 3 of the languages (where the best language in the world finally appears due to the specificity of the priority queue traversal):

Common Algorithms

the algorithm in STL is to standardize the commonly used algorithm, its element scope is any sequence of objects that can be accessed through an iterator or a pointer, but the algorithm only cares about the steps of the operation, there is no relationship with the structure of the data (that is, it does not affect the structure of the container, such as size or storage allocation), and STL has a goal at design time, that is, the algorithm can be reused, and the efficiency should be as high as possible. The STL contains more than 70 algorithms that are highly reusable, including: sorting, finding, arranging, moving, copying, deleting, comparing, and computing .

About its usage:

The first is to include the header file <algorithm>, which defines the various function sets of the algorithm.

Common algorithms:

finding the class  algorithm find/find_if/find_first_of/binary_search/count/ count_if sort and general algorithm   sort/stable_sort/partial_sort/partial_sum/partition/merge/ Reverse Delete and replace algorithm copy /copy_backward/remove/remove_if/swap/ unique permutation combination algorithm prev_permutation / next_permutation collection Operation set_difference /set_union/set_intersection

Simple Application

1. Find

//Binary_search void  Test_binary_search () {  int a[] = {one,2,4,5, 9,0,3,6}; Vector<int> V (A, A + 8); Sort (V.begin (), V.end ()); cout<<binary_search (V.begin (), V.end (), 6); //Results 1}

2. Sorting

//Partiton BOOLIsbigerk (intcurvalue) {     returnCurvalue <3; } voidtest_partition () {vector<int>A; A.push_back (6); A.push_back (5); A.push_back (4); A.push_back (3); A.push_back (2); A.push_back (1); //divide the boundary by 3partition (A.begin (), A.end (), Isbigerk);  for(intI=0; i< a.size (); ++i) cout<<a[i]<<" "; cout<<Endl; //Results: 1 2 4 3 5 6 }   //Sort//Template<class t>//Like this custom to compare//struct Greater//{  //bool Operator () (const t& L, const t& R)//  {  //return l > r;//  } //}; voidtest_sort () {vector<int>v; V.push_back (1); V.push_back (3); V.push_back (4); V.push_back (0); V.push_back (Ten); V.push_back (3); Sort (V.begin (), v.end (), Greater<int>());  for(intI=0; i< v.size (); ++i) cout<<v[i]<<" "; cout<<Endl; //Results://4 3 3 1 0 }

3. Permutation and combination problems

 //Permutation questions//next_permutation the next permutation .  void  test_permutation () {  string str ("ABC");   do {cout<<str.c_str () <<Endl; }while (Next_permutation (Str.begin (), Str.end ())); //Results://ABC//ACB//BAC//BCA//Cab//CBA//Note: There is no effect on duplicate values. AaB The entire permutation is not duplicated. }

4. Collection Operations

Set_difference

About using:

1. Find the different elements in the two collections, all of which come from the first group, not from the second group.

2. Its return value is an iterator it, which points to the last position of the stored result (that is, the different elements that are found). The number of different elements is usually obtained with it-ret.begin ().

 void  test_set_difference () {  int a[] = {1, 4,-1, 5< /c8>, 2};  int b[] = {3, 4, 1, 5, 6};  //+5 Note! Sort (A, A +5);//-1 1 2 4 5Sort (b, + +5);//1 3 4) 5 6Vector<int> V (Ten); Vector<int>:: Iterator it; It=set_difference (A, A +5, B, +5, V.begin ()); //It is-1 2 0 0 0 0 0 0 0 0 End V.resize (It-v.begin ());//-1 2it =V.begin ();  while(It! =V.end ()) {cout<<*it<<" "; ++it; }       // Result: -1 2 }

An overview of the relevant classifications in the algorithm:

Reference:http://www.cplusplus.com/reference/algorithm/

stl--adapter, common algorithm use

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.