C++ Standard Template Library (STL) - commonly used functions under queue, priority_queue, stack, pair, algorithm header files


1. Queue

queue is a queue with first-in-first-out characteristics. To use queue, you need to add #include<queue> and using namespace std;

1. Definition of queue:

queue<typename> name;//typename可以是任意基本数据类型或容器

Access to queue elements:
Since queue itself is a first-in first-out restrictive data structure, STL can only provide front() to access the first element of the queue, and use back() to access the tail element of the queue

#include<queue>
#include<stdio.h>
using namespace std;

int main(){
    queue<int> q;
    for(int i = 1 ; i <= 5 ; i++)
        q.push(i);
    printf("%d",q.front());//1
    return 0;
}

3. push()
push(x): put x into the queue and insert it at the end of the queue

4. pop()
dequeues the first element of the team

#include<queue>
#include<stdio.h>
using namespace std;

int main(){
    queue<int> q;
    for(int i = 1 ; i <= 5 ; i++)
        q.push(i);
    for(int i = 1 ; i <= 3 ; i++)
        q.pop();
    printf("%d",q.front());//4
    return 0;
}

5. Empty()
detects whether the queue is empty, if it is, it returns true, if it is not, it returns false

6. size()
returns the number of elements in the queue

Note: Before using the front() and pop() functions, you must use the empty() function to determine whether the queue is empty, otherwise an error may occur

二、priority_queue

Priority queue, the underlying layer is implemented with a heap. In the priority queue, the head element of the queue must be the one with the highest priority in the current queue. When using it, add #include<queue> and using namespace std;

1. The definition of priority_queue:

priority_queue<typename> name;

2. Access to elements in the priority_queue container:
Unlike queue, the priority queue does not have front() and back() functions, and can only access the first element of the queue through the top() function

#include<queue>
#include<stdio.h>
using namespace std;

int main(){
    priority_queue<int> q;
    q.push(3);
    q.push(4);
    q.push(1);
    printf("%d",q.top());//4
    return 0;
}

3. push():
push(x): make x enter the queue

4. top():
You can get the first element of the team and realize the access to the elements in the container

5. pop():
Dequeue the first element of the team

6. empty():
Check whether the queue is empty, if it is empty, return true, otherwise return false

7. size()
returns the number of elements in the priority queue

8. Element priority setting
(1) Priority setting of basic data types Taking
the int type as an example, the following two definitions are equivalent:

priority_queue<int> q;

priority_queue<int,vector<int>,less<int> > q;

In the second way, vector<int> is the container to carry the underlying data structure, while less<int> is the comparison class for the first parameter, less<int> means that the priority of the larger number is greater, and greater < int > indicates that the priority of the smaller number is greater

#include<queue>
#include<stdio.h>
using namespace std;

int main(){
    priority_queue<int,vector<int>,greater<int> > q;//数字小的优先级越大
    q.push(3);
    q.push(4);
    q.push(1);
    printf("%d",q.top());//1
    return 0;
}

(2) Structure priority setting
If you create a structure with the name and price of the fruit, and now you want to give a high priority to the high price of the fruit, you need to overload the "<" less than sign, and overloading the greater than sign will cause a compilation error.

struct fruit{
    string name;
    int price;
    friend bool operator < (fruit f1 , fruit f2){
        return f1.price < f2.price;
    }
};

Note: The effect of this function in the priority queue is opposite to that of the cmp function in sort. Setting f1.price<f2.price is arranged from small to large, but the effect in the priority queue is that the higher the price, the higher the priority

Example: Priority is given to fruits with low prices

#include<queue>
#include<string>
#include<iostream>
using namespace std;

struct fruit{
    string name;
    int price;
    friend bool operator < (fruit f1 , fruit f2){
        return f1.price > f2.price;
    }
}f1,f2,f3;

int main(){
    priority_queue<fruit> q;
    f1.name = "桃子";
    f1.price = 3;
    f2.name = "梨子";
    f2.price = 4;
    f3.name = "苹果";
    f3.price = 1;
    q.push(f1);
    q.push(f2);
    q.push(f3);
    cout<<q.top().name<<" "<<q.top().price<<endl;
    return 0;
}

insert image description here

**Common use:** can solve some greedy problems, and can also optimize the Dijkstra algorithm

Three, stack

Stack: last-in-first-out container. To use the stack, you must add #include<stack> and add using namespace std;

1. The definition of stack:

stack<typename> name;

2. Access to elements:
The top element of the stack can only be accessed through top()

3. push():
push(x): push x onto the stack

4. pop()
pop() is used to pop the top element of the stack

#include<stdio.h>
#include<stack>
using namespace std;

int main(){
    stack<int> s;
    for(int i = 1 ; i <= 5 ; i++)
        s.push(i);
    for(int i = 1 ; i <=3 ; i++)
        s.pop();
    printf("%d",s.top());//2
    return 0;
}

5. Empty():
Check whether the stack is empty, return true if it is empty, and return false if it is not empty

6. size():
returns the number of elements in the stack

Four, pair

Use a pair when you want to tie two elements together as a composite element, but don't want to define a struct. In other words, pair can actually be regarded as a structure with two elements inside. If you want to use pair, you need to add #include < utility > and using namespace std.

1. Definition of pair:

pair<typename1,typename2> name;

如:
pair<string,int> p;

也可以定义的时候进行初始化:
pair<string,int> p("haha",5);

2. Element access:
There are only two elements in the pair, namely first and second

#include<utility>
#include<iostream>
#include<string>
using namespace std;

int main(){
    pair<string,int> p;
    p.first="haha";
    p.second=5;
    cout<<p.first<<" "<<p.second<<endl;
    p = make_pair("xixi",55);
    cout<<p.first<<" "<<p.second<<endl;
    p = pair<string,int>("heihie",555);
    cout<<p.first<<" "<<p.second<<endl;
    return 0;
}

3. Comparison:
Two pair types can be compared by ==, !=, <, <=, >, >=. The rule is to first use the size of the first as the standard, and only when the first is equal, then judge the size of the second

Common uses:

  • Used in place of binary structs and their constructors
  • Insert as key-value pairs of map
#include<utility>
#include<iostream>
#include<string>
#include<map>
using namespace std;

int main(){
   map<string,int> mp;
   mp.insert(make_pair("heihei",5));
   mp.insert(pair<string,int>("haha",10));
   for(map<string,int>::iterator it = mp.begin();it!=mp.end();it++){
    cout<<it->first<<" "<<it->second<<endl;
   }
   return 0;
}

insert image description here

5. Commonly used functions under the algorithm header file

1、max()、min()、abs():

max(x,y), min(x,y) returns the maximum and minimum values ​​in x, y. And the parameters must be two, if there are three parameters, you can use max(x,max(y,z)).
abs(x) returns the absolute value of x. x must be an integer, if it is a floating point number, please use fabs under the math header file

2、swap():

swap(x,y) is used to exchange the values ​​of x and y

3、reverse():

reverse(it,it2) can reverse the elements of the array pointer between [it,it2) or the elements of the container iterator in the range of [it,it2)

#include<stdio.h>
#include<string>
#include<algorithm>
using namespace std;

int main(){
    string str = "abcdefghi";
    reverse(str.begin()+2,str.begin()+6);
    for(int i = 0 ; i < str.length() ; i++)
        printf("%c",str[i]);//abfedcghi
    return 0;
}

4、next_permutation():

gives the next sequence of a sequence in the full permutation.
For example: full permutation when n=3

123
132
213
231
312
321
#include<stdio.h>
#include<algorithm>
using namespace std;

int main(){
    int a[10]={1,2,3};
    do{
        printf("%d%d%d\n",a[0],a[1],a[2]);
    }while(next_permutation(a,a+3));
    return 0;
}

insert image description here
next_permutation will return false when reaching the last of the full array, which will make it easy to exit the loop

5、fill():

You can assign a certain range in an array or container to the same value. Unlike memset, the assignment here can be any value within the corresponding range of the array type

#include<stdio.h>
#include<algorithm>
using namespace std;

int main(){
    int a[5]={1,2,3,4,5};
    fill(a,a+5,233);
    for(int i = 0 ; i < 5 ; i++)
        printf("%d ",a[i]);
    return 0;
}

6、sort():

is the function used to sort:

sort(首元素地址,尾元素地址的下一个地址,比较函数)

The comparison function can be filled in as needed. If not written, the range given above will be sorted in ascending order by default.

For example: sorting char arrays from large to small (lexicographically)

#include<stdio.h>
#include<algorithm>
using namespace std;

bool cmp(char a , char b){
    return a>b;
}

int main(){
    char a[] = {'T','W','A','K'};
    sort(a,a+4,cmp);;
    for(int i = 0 ; i < 4 ; i++)
        printf("%c",a[i]);//WTKA
    return 0;
}

For example: for the sorting definition of the structure, if x is not equal, it will be sorted according to x from large to small, and if x is equal, it will be sorted according to y from small to large

#include<stdio.h>
#include<algorithm>
using namespace std;

struct node{
    int x,y;
}ssd[10];

bool cmp(node a , node b){
    if(a.x != b.x)
        return a.x > b.x;
    else
        return a.y < b.y;
}

int main(){
    ssd[0].x = 2;
    ssd[0].y = 2;
    ssd[1].x = 1;
    ssd[1].y = 3;
    ssd[2].x = 2;
    ssd[2].y = 1;
    sort(ssd,ssd+3,cmp);
    for(int i = 0 ; i < 3 ; i++)
        printf("%d %d\n",ssd[i].x,ssd[i].y);
    return 0;
}
// 2 1
// 2 2
// 1 3

Sorting of containers: In STL, only vector, string, and deque can use sort, because containers such as set and map are inherently ordered

#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;

bool cmp(int a , int b){
    return a>b;
}

int main(){
    vector<int> vi;
    vi.push_back(3);
    vi.push_back(1);
    vi.push_back(2);
    sort(vi.begin(),vi.end(),cmp);
    for(int i = 0 ; i < 3 ; i++)
        printf("%d ",vi[i]);
    return 0;
}

7、lower_bound()、upper_bound()

Needed to be used in an ordered array or container.
lower_bound(first, last, val) finds the position of the first element whose value is greater than or equal to val within the [first, last) range of the array or container, if it is an array, it returns the pointer of this position, if it is a container, it returns the The position iterator
upper_bound(first, last, val) finds the position of the first element whose value is greater than val within the [first, last) range of the array or container. If it is an array, it returns the pointer of this position. If it is a container, Returns an iterator to the position
If not found, returns a pointer or iterator to the position where the element can be inserted

#include<stdio.h>
#include<algorithm>
using namespace std;

int main(){
    int a[10] = {1,2,2,3,3,3,5,5,5,5};
    //寻找-1
    int* lowerPos = lower_bound(a,a+10,-1);
    int* upperPos = upper_bound(a,a+10,-1);
    printf("%d,%d\n",lowerPos-a,upperPos-a);//0,0

    //寻找3
    lowerPos = lower_bound(a,a+10,3);
    upperPos = upper_bound(a,a+10,3);
    printf("%d,%d\n",lowerPos-a,upperPos-a);//3,6

    return 0
}

Guess you like

Origin blog.csdn.net/weixin_46025531/article/details/122799564