Algorithm notes - STL and frequently asked questions

vector

vector<typename> name

functionfunctionTime complexity
push_back(x)Add an element after the vectorO(1)
pop_back()Delete the tail element of the vectorO(1)
size()Get the number of elements of the vectorO(1)
clear()Empty all elements in the vectorO(N), N is the number of vector elements
insert(it,x)Insert an element x into any iterator it of the vectorO(N)
erase(it)Delete element at iterator itO(N)
erase(first,last)Delete all elements in [first, last]O(N)

queue

queue<typename> name

functionfunctionTime complexity
push(x)Team up xO(1)
front()Get the first element of the team and call the empty() function before use.O(1)
back()Get the queue element and call the empty() function before use.O(1)
pop()Get the first element out of the teamO(1)
empty()Check whether the queue is emptyO(1)
size()Returns the number of elements in the queueO(1)

priority_queue

priority_queue<typename> name

functionfunctionTime complexity
push(x)Put x in the teamO(logN), N is the number of elements in the current priority queue
top()Get the first element of the team (that is, the top element) and call the empty() function before use.O(1)
pop()Get the first element of the team (i.e. the top element) out of the teamO(logN), N is the number of elements in the current priority queue
empty()Check whether the priority queue is emptyO(1)
size()Returns the number of elements in the priority queueO(1)

Priority_queue < int > Q the higher the number, the higher the priority

Priority_queue < int, vector < int >, less < int > > Q the greater the number, the greater the priority

Priority_queue < int, vector < int >, greater < int > > Q the smaller the number, the greater the priority

#include <iostream>
#include <stdio.h>
#include <queue>


using namespace std;


struct fruit
{
    string name;
    int price;
    friend bool operator < (fruit f1,fruit f2)//Only the less than sign can be overloaded
    {
        return f1.price>f2.price;
        //Specific understanding: if f1. Price > f2. Price is true, then f1 is considered "<" f2, so f1 should be after f2
        //This is the opposite of cmp in the sort function
    }
} f1,f2,f3;

int main()
{    priority_queue<fruit> q;
    f1.name = "Peach";
    f1.price = 3;
    f2.name = "Pear";
    f2.price = 4;
    f3.name = "Apple";
    f3.price = 1;
    q.push(f1);
    q.push(f2);
    q.push(f3);
    //printf("%s %d\n",q.top().name,q.top().price);
    cout<<q.top().name<<" "<<q.top().price<<endl;
    return 0;
}

Purpose of priority_queue: solve greedy problems; optimize Dijkstra algorithm.

stack

stack< typename > name

functionfunctionTime complexity
push(x)Stack xO(1)
top()Get stack top elementO(1)
pop()Pop up stack top elementO(1)
empty()Check whether the stack is emptyO(1)
size()Returns the number of elements in the stackO(1)

set

The elements in set are automatically sorted incrementally, and duplicate elements are automatically removed

set iterator access method:

set<typename>::iterator it;

set<int>::iterator it;

set<char>::iterator it;

int main(){
      set<int> st;
      for(set<int>::iterator it=st.begin(); it!=st.end(); it++){
        printf("%d",*it);    
    }  
}
functionfunctionTime complexity
insert(x)Insert x into the set container and automatically increment and de duplicateO(logN)
find(value)Returns the iterator with the corresponding value of value in setO(logN)
erase(it)Delete a single element, and it is the iterator of the element to be deletedO(1)
erase(value)Delete a single element, and value is the value of the element to be deletedO(logN)
erase(first,last)Delete all elements in an interval, i.e. [first, last)O(last-first)
size()Used to obtain the number of elements in the setO(1)
clear()Used to empty all elements in the setO(N), where N is the number of elements in the set

map

Map can map any base type (including STL container) to any base type (including STL container).

map<typename1,typename2> mp;

If it is a string to integer mapping, you must use string instead of char array.

map<string,int> mp;

There are generally two ways to access elements in the map container:

  1. Access through subscript; when establishing a mapping, you can directly use map['c'] = 20, which is the same as an ordinary array.
  2. Access through iterators;

    map<typename1,typename2>::iterator it;

    Use it - > first to access the key and it - > second to access the value.

The map is automatically sorted by key from small to large.

functionfunctionTime complexity
find(key)Returns the iterator of the mapping whose key is keyO(logN), N is the number of maps in the map
erase(it)Delete a single element, and it is the iterator of the element to be deletedO(1)
erase(first,last)Delete the left closed right open interval [first, last], and both first and last are iteratorsO(last-first)
size()Used to obtain the logarithm of the mapO(1)
clear()Used to empty all elements in the mapO(N), N is the number of maps in the map

string

"XYZ > ABC" holds because "X" > "a“

How to add or delete characters after a variable of type string

string a;
a.push_back('a');
a.pop_back()

string variables can only be enclosed in double quotes, not single quotes:

string a = 'abc';//Error, python can do this, c + + can't
string b = "abc";//correct
class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        int in_degree[numCourses];
        vector<int> graph[numCourses];
        int nums = 0;
        queue<int> topo;
        for(int i=0; i<numCourses; i++){
            in_degree[i] = 0;
        }
        for(vector<int> tmp:prerequisites){
            graph[tmp[0]].push_back(tmp[1]);
            in_degree[tmp[1]]++;
        }
        for(int i=0; i<numCourses; i++){
            if(in_degree[i]==0){
                topo.push(i);
            }
        }
        while(!topo.empty()){
            int now = topo.front();
            topo.pop();
            nums++;
            for(int i=0; i<graph[now].size(); i++){
                in_degree[graph[now][i]]--;
                if(in_degree[graph[now][i]] == 0){
                    topo.push(graph[now][i]);
                }
            }
        }
        if(nums==numCourses){
            return true;
        }
        return false;
    }
};

Bibliography: algorithm notes

Tags: C++ STL

Posted on Mon, 06 Dec 2021 01:01:34 -0500 by fiorefrank