# c + + algorithm training STL library

Posted by aron on Tue, 08 Mar 2022 19:54:10 +0100

## 1. STL algorithm library (c + + feature)

### Pair (binary, element pair)

Located in the header file < iostream >, it is used to represent a binary or element pair
1.1 using pair
Define a pair object to represent a plane coordinate point:

```pair<double, double> p;
cin >> p.first >> p.second;
```

2.1 sorting

```int cmp(pair<int,int > a,pair<int ,int > b){
return a.second<b.second;
}
```

### Vector (class array)

vector contains a series of continuously stored elements, which are very similar to arrays.
Access the element or insert the element constant level at the end. The inserted element is a linear level.

Note that the tail element of the vector is

```vector<int> ve;
vector<int>::iterator::iter;
iter=ve.end()-1;    //There must be a reduction here
cout<*ite<<endl;
```

2.vector operation

```cvec.begin();    //Returns the iterator of the first element
vec.end();
vect.empty();
vec.front();    //Returns the first element
vec.push_back();    //Add an element at the end
vec.pop_back();     //Remove last element

#include<bits/stdc++.h>
using namespace std;

vector<int> vec
int main(){
vec.push_back(1);       //Tail insert element
vec.push_back(2);
vec.push_back(5);

//iterator
vector<int>::iterator ite;
for(ite=vec.begin();ite!=vec.end();++ite){
cout<<*ite<<endl;
}

//Insert element, insert a before the i+1 element
vec.insert(vec.begin()+i,a);
//Delete element
vec.erase(vec.begin()+2);  //Delete the third element

vec.size();
vec.clear();

return 0;
}

//The element of vector can also be a structure, but the structure must be defined as global
#include<bits/stdc++.h>
using namespace std;
typedef struct rect{
int id,length,width;
//If the vector element is a structure, you can define a comparison function inside the structure
bool operator< (const rect &a)  const
{
if(id!=a.id)
return id<a.id;
else
{
if(length!=a.length)
return length<a.length;
else
return width<a.width;
}
}
}Rect;
int main(){
vector<Rect> vec;
Rect rect;
rect.id=1;
rect.length=2;
rect.width=3;
vec.push_back(rect);
vector<Rect>::iterator it=vec.begin();
cout<<(*it).id<<(*it).length<<(*it).width<<endl;
return 0;
}
```

(1) Flip the element using reverse:

```reverse(vec.begin(),vec.end());
```

(2) Sort using sort: header file #include < algorithm >

sort(vec.begin(),vec.end()); (the default is in ascending order, i.e. from small to large)

You can override the sort comparison function to compare in descending order, as follows:

Define sorting comparison function:

```bool Comp(const int &a,const int &b)
{
return a>b;
}
```

When calling sort (VEC. Begin()), VEC End(), COMP), which will sort in descending order.

### set

The data will be automatically de duplicated and sorted after being stored in it.
Although set automatically removes duplicates, you can still use count() to find the number of duplicate data at a certain point. Duplicate elements are not allowed in set container, and duplicate elements are allowed in multiset
When accessing elements, set cannot be accessed according to subscripts, but can only be accessed through traversal. We want to access the elements inside the set according to the subscript. We can store the elements inside the set in the vector.

set common operations:

```set<int> s;
set<double> ss;
multiset<int> ms;     //Allow repetition

set Basic operation of:
s.begin()                               //Returns an iterator that points to the first element
s.clear()                               //Clear all elements
s.count()                               //Returns the number of a value element
s.empty()                               //Returns true if the collection is empty
s.end()                                 //Returns an iterator that points after the last element, not the last element
s.erase()                               //Delete elements in the collection
s.find()                                //Returns an iterator that points to the found element
s.insert()                              //Insert element in collection
s.lower_bound()                         //Returns an iterator pointing to the first element greater than (or equal to) a value
s.size()                                //Number of elements in the collection
s.swap()                                //Swap two set variables
s.upper_bound()                         //Returns an iterator that is greater than a value element

set<int> s;

s.erase(2);        //Delete element with key value 2
s.clear();

//Element retrieval: find(), if found, return the position of the key value iterator; otherwise, return the position after the last element.

set<int>::iterator it;
it=s.find(5);    //Find element with key value of 5
if(it!=s.end())    //find
cout<<*it<<endl;

//Custom comparison function
(1)Element is not a structure:
Example:
//The user-defined comparison function myComp overloads the "()" operator
struct myComp
{
bool operator()(const your_type &a,const your_type &b)
[
return a.data-b.data>0;
}
}
set<int,myComp>s;
......
set<int,myComp>::iterator it;
(2)If the element is a structure, you can directly write the comparison function in the structure.
Example:
struct Info
{
string name;
float score;
//Overload the "<" operator to customize the collation
bool operator < (const Info &a) const
{
//Rank by score from large to small
return a.score<score;
}
}
3.give an example

#include<iostream>
#include<set>
#include<cstdio>
using namespace std;
int main(){
set<int> s;

//Insert element
s.insert(1);
s.insert(3);
s.insert(5);

//Find element
set<int>::iterator ite;

ite=s.find(1);  //Find element with key value of 1
if(ite==s.end()) puts("not find");
else puts("find");

ite=s.find(2);
if(ite==s.end()) puts("not find");
else puts("find");

//Delete element
s.erase(3);

//Other ways to find elements
if(s.count(3)!=0) puts("find");
else puts("no find");

//Traverse all elements
for(ite=s.begin();ite!=s.end();++ite)
cout<<*ite<<endl;

return 0;

#include<bits/stdc++.h>
using namespace std;
set<int> s;
int main(){
s.insert(1);
s.insert(3);
s.insert(4);
cout<<*lower_bound(2)<<endl;  //Output 3, return the first greater than or equal to
cout<<*lower_bound(3)<<endl;  //Output 3
cout<<*upper_bound(3)<<endl;  //Output 4, return the first greater than
return 0;
}

```

### map(key - value)

map is an ordered and non repetitive Association container.
Map is an associated container of STL. It provides one-to-one data processing capability (the first can be called a keyword, each keyword can only appear once in the map, and the second may be called the value of the keyword). Due to this feature, it is possible to provide a fast channel in programming when we process one-to-one data.

Functions of map
Automatically establish Key - value correspondence. Key and value can be any type you need.

give an example

```map<string,int> mp;
string ss;
for(int i=0;i<n;i++){
cin>>ss;
mp[ss]=i;
}

//insert data
mp["a"]=1;
mp.insert(map<string,int>::value_type("b",2));

//Find data
int tmp=mp["a"];
map::iterator ite;
ite.find("a");
ite->second=j;  //Note that the value of the key cannot be modified unless deleted

#include<bits/stdc++.h>
using namespace std;
int main(){
map<int,string> mpstudent;
mpstudent="student1";
mpstudent="student2";
mpstudent="student3";
//iterator
map<int,string>::iterator ite;
for(ite=mpstudent.begin();ite!=mpstudent.end();++ite)
cout<<ite->first<<" "<<ite->second<<endl;
return 0;
}

be careful:
STL By default, the less than sign is used to sort. When the keyword is a structure, there will be problems related to sorting.
Because it has no less than operation, insert And other functions can't pass when compiling

#include <map>
#include <cstring>
using namespace std;

typedef struct tagStudentInfo
{
int nID;
string strName;

bool operator < (tagStudentInfo const & _A)const
{
// This function specifies the sorting strategy, sort by nID, and sort by strName if NIDS are equal.
if (nID < _A.nID)
return true;
if (nID == _A.nID)
return strName.compare(_A.strName) < 0;

return false;
}

} StudentInfo, *PStudentInfo;  // Student information

void main()
{
// Mapping scores with student information
map<StudentInfo, int> mapStudent;
StudentInfo studentInfo;
studentInfo.nID = 1;
studentInfo.strName = "student_one";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));
studentInfo.nID = 2;
studentInfo.strName = "student_two";
mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));
}
```

### queue

Characteristics of the queue:
fifo

Queue operation

```q.size();
q.empty();
q.push(k);   //Insert k at the end of the line
q.pop();     //Delete the first element of the queue
q.front();      //Returns the first element of the queue
q.back();   //Returns the end element of the queue

```

### priority_queue priority queue

characteristic:
Auto sort (default from large to small)
Operation of priority queue

```//node is a structure, and "<" must be overloaded here
priority_queue <node> q;
//The two > > should not be written together, > > is the shift right operator
priority_queue <int,vector<int>,greater<int> > q;  //from small to large
priority_queue <int,vector<int>,less<int> > q;      //From big to small

```

```#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y;
bool operator <(const node &a) const{
return x>a.x;
}
}k;
priority_queue <node> q;
//priority_queue <int,vector<int>,greater > q;
int main(){
k.x=1;k.y=2;  q.push(k);
k.x=2;k.y=1;  q.push(k);
k.x=3;k.y=4;  q.push(k);
while(!q.empty()){
node t;
t=q.top();
q.pop();
cout<<"("<<t.x<<","<<t.y<<")"<<endl;
}
return 0;
}
```

### stack

In and out

```#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<int> S;
S.push(3);
S.push(7);
S.push(1);
cout << S.size() << " ";

cout << S.top() << " ";    //Return stack top element
S.pop();                   //Remove and delete elements from the stack

cout << S.top() << " ";
S.push(5);                 //Add elements to the stack

return 0;

}

```