C++STL knowledge set

Posted by vombomin on Mon, 07 Mar 2022 15:09:08 +0100

STL

Hey, c + + long time no see, meet you again familiar and strange. The feeling of practicing many brush questions fades a little, and you need to be familiar with the actual questions again. This article will be continuously updated
Today, let's remedy the concept of STL in time to facilitate more efficient problem brushing in the future.

In STL, the iterator in the container is passed to the algorithm, and the elements are accessed / traversed through the iterator in the algorithm

[tutorial reference 1]
[refer to tutorial 2]
Of course, the final reference is the official document: https://www.cplusplus.com/reference/

premise

  • output iterator (written as: OutIt): you can modify the container element it points to
  • input iterator (recorded as: InIt): it can only read the container element it points to
  • Predicate: the return value of the function is Bool; Pred unary predicate, an element as a function of parameters; Binred binary predicate

string

string s;
string s5 = s1 + s2; //Splicing
s2.insert(5, "bbb"); //Insert at subscript 5
s2.erase(5);  // Delete 5 positions and all subsequent
s3.erase(5, 3); //The length of the substring to delete is 3
s1.find(s2,5) ; //Find the s2 string starting at position 5
// find (const string& str, size_t pos = 0)
//The return value of find() is the position of the letter in the parent string. If it is not found, the integer - 1 is returned

s.front()='1';
s.back();

vector

  • Overview: dynamic array to achieve fast positioning + tail add / delete elements
vector<int> v;
vector<int> v(5,10); //The content of 5 elements is 10
//iteration
for( auto it=v.begin();it!=v.end();it++){
    cout<<*it<<endl;
}
v.push_back(10);
v.pop_back();//Vector tail deletion
v.insert(v.begin(),10); //Insert data at the front end 10
v.insert(v.begin(),k.begin(),k.end()); //Insert the entire contents of vector K at the front of v
v.erase(v.begin());  //Delete element
//erase (iterator position); 
//erase (iterator first, iterator last);
v.clear(); //empty
// Enter the method of vector!!
vector<int> v(n);
for(int& i:v){
    cin>>i;
}
// Find the minimum element
*min_element(v.begin(), v.end()); 

list

  • Overview: bidirectional linked list, add / delete at any position

    [you can't access elements randomly with the following table!! there is no find]

list<int> li;
li.empty(); //Air judgment
li.size();
li.push_front(10);
li.pop_front();  //Addition and deletion before linked list
li.push_back(10);
li.pop_back(); //Add / delete after linked list
//insert and erase are the same as vector
li.sort(); //Ascending sort
li.reverse(); //Descending order (no vector)

deque

  • It supports random access and can be inserted and deleted internally
deque<int> d;
//Static operation
d.size();
d.empty();
d.front();
d.back();
d[idx];
//Dynamic operation
d.insert(pos,elem);
d.push_back(elem);
d.pop_back(elem);
d.erase(pos);
d.erase(beg,end);

stack

  • Add / delete elements only at the tail
  • It can be implemented based on deque, list or vector.
stack<int> s;
s.empty();
s.top(); //Return stack top element
s.pop(); //Stack top element release
s.push(); //Push 

Priority_queue

  • Add elements in the tail and delete elements in the head, and sort automatically (the largest element in the head)
  • Initialization → priority_ Queue < T, Container, compare > / / T data type, Container container type (must be an array implemented Container: vector, deque), compare comparison method
struct cmp
{ //This comparison is represented by a structure
    bool operator()(int &a, int &b) const
    {
        return a > b;
    }
};
  
priority_queue<int,vector<int>,cmp> q;    //Using custom comparison methods
priority_queue< int, vector<int>, less<int> > q;
priority_queue< int, vector<int>, greater<int> > pq;
q.pop();
q.push();
q.top();

set

  • Red black tree implementation, each time the data is inserted, it will be sorted automatically and the data is unique
set<int> s;
// C11 implementation
for (auto it=s.cbegin(); it!=s.cend(); ++it)
      cout << *it;
s.insert();
s.erase(s.begin());  //Use the iterator method to delete the first element
s.erase(s.begin(),s.end());     //Delete a paragraph, here is to delete all
cout<< *s.find(4) ; //Return iterator
s.erase(s.find(4)); //Delete found elements

map

//Find examples of phone calls
map<string,int> m;
m["zhou"]=1234;
m["xiao"]=2345;
m["weng"]=3456;
for(pair<string,int>item: m){  //Traversal output
    cout<<item.first<<":"<<item.second;
} 
string name;
cin >> name;
map<string,int>::const_iterator it;
it=m.find(name);
if(it==m.end()) cout<<"not found";
else cout << it->first << ": " << it->second << endl; // find
//Sort, convert to vector!
bool cmp(const PAIR& p1,const PAIR& p2){
	if(p1.second==p2.second) return p1.first<p2.first;
	return p1.second>p2.second;
}
...
map<int,int> m;
vector<PAIR> ans(m.begin(),m.end());
sort(ans.begin(),ans.end(),cmp);
for(PAIR& i:ans){
    cout<<i.first<<" "<<i.second<<endl;
}

Pair class

  • Pair combines a pair of values (which can have different data types) and into one value
map<char,int> m;
m.insert(pair<char,int>('a',10));
//Return two elements with first and second
pair<int,int> p(10,20);
cout<<p.first<<" "<<p.second;
//make_pair generate pair
pair<int,int> p(10,20);
cout<<p.first<<" "<<p.second<<endl;

array class

  • The new sequence container in C++11 standard is based on ordinary array and has a fixed size
array<int,2> a;
a.begin();a.end();a.size();a.empty();
//Practical usage [mostly used when point coordinates are needed]
set<array<int,2>> s;
s.insert({k1,k2}); 
cout<<s.size();

Other functions

int sum = accumulate(vec.begin() , vec.end() , 42);//accumulate takes three parameters: the first two parameters specify the range of elements to be accumulated, and the third parameter is the initial value of accumulation.
//Convert integer to string
int i=10;
if(to_string(i).find("7")==-1) ... //If 7 is not found in integer i
//Determine whether char is a character
if(isdigit(c)) ...
//Structure Sorting

struct Point{
	int x,y;
    //Overload + operator
    const Point operator+(Point other){
		Point result(this->x+other.x,this->y+other.y);
		return result;
	} 
    
};
//In descending order, great is in front 
bool GreaterSort(Point a,Point b){
	if(a.x==b.x)return a.y>b.y;
	return  a.x>b.x;} 

int main(){
	int n;
	cin>>n;
	vector<Point> v(n);
	for(Point &i:v){
		cin>>i.x>>i.y;
	}
	sort(v.begin(),v.end(),GreaterSort);
	 
	for(Point i:v){
		cout<<i.x<<" "<< i.y<<endl;
	}
	

Summary:

intlong long int
byte48
Representation range- 2147483648 ~ -2147483647-9223372036854775808 ~ 9223372036854775807
magnitude1 0 9 {10^{9}}1091 0 21 {10^{21}}1021

find() function

//Prototype: inputiterator find (inputiterator first, inputiterator last, const T & VAL);
//Return: find the iterator location of the element
vector<int>::iterator it;
it = find(myvector.begin(), myvector.end(), 30);

next()/prev() function

  • Returns a new iterator n elements away from the it iterator.
    • next(): n refers to regular backward search, and negative refers to forward search
    • prev(): opposite to next
template <class BidirectionalIterator>
    BidirectionalIterator prev (BidirectionalIterator it, typename iterator_traits<BidirectionalIterator>::difference_type n = 1);

template <class ForwardIterator>
    ForwardIterator next (ForwardIterator it, typename iterator_traits<ForwardIterator>::difference_type n = 1);


//Gets an iterator 2 elements away from the IT iterator. Since 2 is a positive number, newit is on the right side of it
list<int> l; ...
auto newit = next(l.begin(), 2);
cout << "next(it, 2) = " << *newit << endl;

erase function

  • Returns an iterator that eliminates the last position
iterator erase (iterator position);
iterator erase (iterator first, iterator last);

Topics: C++ Algorithm data structure