Double linked list
List
begin() and end():
An iterator pointing to the starting position of the container is obtained by calling the member function begin() of the list container. The next position at the end of the list can be obtained by calling the end() function of the list container, which is equivalent to the nth + 1st position a[n] in int a[n]. In fact, it does not exist and cannot be accessed. It is often used as a condition for judging the end of the loop.
push_back() and push_front():
Use the member function push of list_ Back and push_front inserts an element into the list. Where push_back() is inserted from the end of the list, while push_ The implementation of front () is inserted from the head of the list.
empty():
Use empty() to determine whether the list is empty.
front() and back()
pop_back and pop_front()
reverse():
Reverse the list through reverse().
merge():
Merge two linked lists and make them in ascending order by default (you can also change it), l1.merge(l2, greater()); After the call, l2 becomes empty. The elements in l1 contain the elements in l1 and l2, and are arranged in descending order. In addition, greater () can be changed or not arranged in ascending order (for example, in structure arrangement)
bool listsort(int a,int b){ if(a>b) return true; return false; } int main () { list<int> IntList; list<int> IntList2(3,5); for( int i=0; i < 10; i++ ) IntList.push_front( i); IntList.merge(IntList2, listsort); for(iter=IntList.begin();iter!=IntList.end();iter++){ cout<<*iter<< " "; } cout<<endl; return 0; }
insert():
Insert one or more elements at the specified location (three overloads):
l1.insert(l1.begin(),100); stay l1 Insert 100 at the start of the. l1.insert(l1.begin(),2,200); stay l1 Insert two 100's at the beginning of the. l1.insert(l1.begin(),l2.begin(),l2.end());stay l1 Insert from l2 Elements at all positions from start to end.
Stack
Stack
Out of stack: push()
Stack pressing: pop()
Whether the stack is empty: empty()
Stack size: size()
Access stack top: top()
queue
code implementation
#include <iostream> #define elemtype int #define MAX 10 using namespace std; struct Queue { elemtype q[MAX]; int front = 0; int rear = 0; }; //Determine whether the queue is full bool isfull(Queue Q) { if ((Q.rear + 1) % MAX == Q.front) { return true; } else { return false; } } // Destroy queue void destroy(Queue &Q) { delete &Q; cout << "DESTROYED" << endl; } // Empty queue void erase(Queue &Q) { Q.front = 0; Q.rear = 0; cout << "ERASED" << endl; } // Get queue header element elemtype Qhead(Queue Q) { return Q.q[Q.front]; } // Insert element at end of queue void Qenter(Queue &Q, elemtype n) { if (isfull(Q)) { cout << "QUENE IS FULL" << endl; } else { Q.q[Q.rear] = n; Q.rear = (Q.rear + 1) % MAX; cout << "ENTERED" << endl; } } // Delete queue header element elemtype Qdelete(Queue &Q) { if (Qlenth(Q) == 0) { cout << "QUENE IS EMPTY" << endl; return -1; } else { int result = Q.front; Q.front = (Q.front + 1) % MAX; cout << "DELETED" << endl; return Q.q[result]; } }
Queue
back() returns the last element
empty() returns true if the queue is empty
front() returns the first element
pop() deletes the first element
push() adds an element at the end
size() returns the number of elements in the queue
sort
sort()
The template of the sort function has three parameters:
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
(1) The first parameter, first, is the starting address of the array to be sorted.
(2) The second parameter, last: is the end address (the address of the last data after the last data)
(3) The third parameter comp is the sorting method: it can be in ascending or descending order. If the third parameter is not written, the default sorting method is to sort from small to large.
struct node { int data; }; bool cmp(node a, node b) { return a.data > b.data;//From big to small }
Tree and binary tree
Binary tree
//BinaryTree struct Tree { char data; Tree *lchild; Tree *rchild; }; //Preorder traversal binary tree void PreOrder(Tree *T) { if (T != NULL) { cout << T->data << ' '; PreOrder(T->lchild); PreOrder(T->rchild); } } //Traversing binary tree by layer void LevelOrder(Tree *T) { queue<Tree *> Q; Q.push(T); while (!Q.empty()) { Tree *t = Q.front(); Q.pop(); cout << t->data << ' '; if (t->lchild != NULL) { Q.push(t->lchild); } if (t->rchild != NULL) { Q.push(t->rchild); } } } //Duplicate binary tree Tree* Tcopy(Tree *T) { if (T == NULL) { return NULL; } else { Tree *copy = new Tree; copy->data = T->data; copy->lchild=Tcopy(T->lchild); copy->rchild=Tcopy(T->rchild); return copy; } } //Count nodes int Tcount_node(Tree*T) { if(T==NULL) { return 0; } else { return Tcount_node(T->lchild) + Tcount_node(T->rchild) + 1; } } //Count the number of leaves int Tcount_leaf(Tree*T) { if(T==NULL) { return 0; } if(T->lchild==NULL&&T->rchild==NULL) { return 1; } else { return Tcount_leaf(T->lchild) + Tcount_leaf(T->rchild); } }
Hash table
The < operator is overloaded with map for the structure, and unordered for the structure_ Map overload = = operator
unordered_map
unordered_map The iterator of is a pointer to this element and obtains its value through the iterator. 1 unordered_map<Key,T>::iterator it; 2 (*it).first; // the key value (of type Key) 3 (*it).second; // the mapped value (of type T) 4 (*it); // the "element value" (of type pair<const Key,T>) Its key values are iterators first and second Properties. 1 it->first; // same as (*it).first (the key value) 2 it->second; // same as (*it).second (the mapped value) Member function: =================iterator ========================= begin Returns an iterator that points to the beginning of the container( iterator) end Returns an iterator pointing to the end of the container cbegin Returns a constant iterator that points to the beginning of the container( const_iterator) cend Returns a constant iterator pointing to the end of the container =================Capacity================ size Returns the number of valid elements max_size return unordered_map Maximum number of elements supported empty Judge whether it is empty =================Element access================= operator[] Access element at Access element =================Element modification================= insert Insert element erase Delete element swap Exchange content clear Empty content
int main() { //Note: C++11 only supports bracket initialization unordered_map<int, string> myMap={{ 5, "Zhang Da" },{ 6, "Li Wu" }};//Assignment with {} myMap[2] = "Li Si"; //Use [] for single insertion. If the key value 2 already exists, the assignment will be modified. If not, it will be inserted. myMap.insert(pair<int, string>(3, "Chen er"));//Insert using insert and pair //Use of traversal output + iterator auto iter = myMap.begin();//auto automatically recognizes as iterator type unordered_map < int, string >:: iterator while (iter!= myMap.end()) { cout << iter->first << "," << iter->second << endl; ++iter; } //Find elements and output the use of + iterators auto iterator = myMap.find(2);//find() returns an iterator pointing to 2 if (iterator != myMap.end()) cout << endl<< iterator->first << "," << iterator->second << endl; system("pause"); return 0; }
map
begin() returns an iterator that points to the map header
clear() deletes all elements
count() returns the number of occurrences of the specified element
empty() returns true if the map is empty
end() returns the iterator that points to the end of the map
erase() deletes an element
find() finds an element
lower_bound() returns the key value > = the first position of the given element
rbegin() returns an inverse iterator that points to the tail of the map
rend() returns an inverse iterator that points to the map header
size() returns the number of elements in the map
upper_bound() returns the key value > the first position of a given element
To determine whether a data (keyword) is displayed in the map
The first method is to use the count function to determine whether the keyword appears. The disadvantage is that it is unable to locate the location where the data appears. Due to the characteristics of map and the one-to-one mapping relationship, the return value of the count function is only two, either 0 or 1. In case of occurrence, of course, 1 is returned
The second is to use the find function to locate the location where the data appears. It returns an iterator. When the data appears, it returns the iterator where the data is located. If there is no data to be found in the map, the iterator it returns is equal to the iterator returned by the end function.
Priority queue
In the priority queue, the elements with higher priority go out of the queue first.
The standard library uses the < operator of element types by defau lt to determine the priority relationship between them.
priority_queue<int>q;
Output elements from small to large
At this point, we can pass in a comparison function
priority_queue<int, vector<int>, greater<int> >q;
Custom priority
Compare priorities in elements by customizing the operator < operator
struct node { friend bool operator< (node n1, node n2) { return n1.priority < n2.priority; } int priority; int value; };
In this structure, value is the value and priority is the priority.
Joint search set
initialization
int fa[MAXN]; inline void init(int n) { for (int i = 1; i <= n; ++i) fa[i] = i; }
query
int find(int x) { if(fa[x] == x) return x; else return find(fa[x]); }
Merge (path compression)
int find(int x) { if(x == fa[x]) return x; else{ fa[x] = find(fa[x]); //Set parent node as root node return fa[x]; //Return parent node } }
chart
dijkstra algorithm (shortest path)
#include <bits/stdc++.h> #define INF 1000000 using namespace std; int flag[1010]; int dis[1010]; int graph[1010][1010]; int n; void dijkstra() { memset(flag, 0, sizeof(flag)); for (int i = 1; i <= n; i++) { dis[i] = INF; } dis[1]= 0; for (int i = 1; i <= n; i++) { int find, min = INF; for (int j = 1; j <= n; j++) { if (!flag[j] && dis[j] <= min) { min = dis[j]; find = j; } } flag[find] = 1; for (int j = 1; j <= n; j++) { if (dis[j] > dis[find] + graph[find][j]) { dis[j] = dis[find] + graph[find][j]; } } } } int main() { int m; cin >> n >> m; memset(graph, INF, sizeof(graph)); for (int i = 0; i < m; i++) { int x, y, d; cin >> x >> y >> d; if (d < graph[x][y]) { graph[x][y] = graph[y][x] = d; } } dijkstra(); if (dis[n] != INF) { cout << dis[n]<<endl; } else { cout << "-1" << endl; } return 0; }
prime algorithm (minimum spanning tree)
#include <iostream> #include <fstream> using namespace std; #define MAX 100 #define MAXCOST 0x7fffffff int graph[MAX][MAX]; int prim(int graph[][MAX], int n) { int lowcost[MAX]; int mst[MAX]; int i, j, min, minid, sum = 0; for (i = 2; i <= n; i++) { lowcost[i] = graph[1][i]; mst[i] = 1; } mst[1] = 0; for (i = 2; i <= n; i++) { min = MAXCOST; minid = 0; for (j = 2; j <= n; j++) { if (lowcost[j] < min && lowcost[j] != 0) { min = lowcost[j]; minid = j; } } cout << "V" << mst[minid] << "-V" << minid << "=" << min << endl; sum += min; lowcost[minid] = 0; for (j = 2; j <= n; j++) { if (graph[minid][j] < lowcost[j]) { lowcost[j] = graph[minid][j]; mst[j] = minid; } } } return sum; }