Summary of common C++ functions & techniques (continuously updated...)

This article is used to summarize and record the skills and commonly used functions that I have used in the process of brushing questions and developing based on C++.
I will keep updating!

grammar related

1. Closure closure

Closures are supported since C++11. CanGet the caller's context without passing parameters, defining functions within functions, etc. In LeetCode, it is very common for the definition of the cmp function in the sort function, the definition of the recursive function, etc.

// 常用的两种形式

// 作为函数的参数,直接定义
// 常用于sort函数中cmp函数的定义
sort(v.begin(), v.end(), [](int a, int b) {
    
    
	return a < b;
});

// 在函数中定义函数
// 常用于递归函数的定义
void a(){
    
    
	vector<int> array;
	function<bool(int)> fun = [&](int i)
    {
    
    
	    if (array[i] > 0)
	        return array[i] == 2;
	};
	return;
}

It can be seen that in the second example, the fun function is a bool type function, and the parameter is an int type. The fun function does not pass the array array parameter, but it can directly call the array array of the context.
Among them, brackets [] are capture lists, and the two common meanings are:
[]: capture nothing
[&]: capture all variables, all captured by reference, that
is, the capture list works when passing context parameters.

2. Integer division and remainder operations of negative integers

The rounding of C++ division usesround towards zero: Take the integer closest to the exact value in the direction of 0, in other words, the decimal part is discarded, so it is also called truncation and rounding.
In this case, 5/3=1, -5/-3=1, -5/3=-1, 5/-3=-1.

3. Dynamic allocation and deletion of memory

The new and delete operators are operators used to dynamically allocate and deallocate memory.
When using the new operator you mustknown data types, the new operator will apply for enough storage space from the system heap area, if the application is successful, it will return the first address (pointer) of the memory block, if the application is unsuccessful, it will return a zero value.
The format for dynamic allocation of arrays is:

Pointer variable name = new type name [subscript expression];
delete [ ] pointer variable name pointing to the array;

The square brackets in the two formulas are very important, and they must be used in pairs. If the square brackets are missing in the delete statement, because the compiler thinks that the pointer is a pointer to the first element of the array, there will be a problem of incomplete recycling ( Only the space occupied by the first element is recovered), and after adding square brackets, it is converted into a pointer to the array, and the entire array is recovered.
The square brackets of delete [] do not need to fill in the number of array elements, the system knows it by itself. Even if written, the compiler ignores it.

int *a = new int;
delete a; //释放单个int的空间

int *a = new int[5];
delete []a; //释放int数组空间

ListNode* a = new ListNode(); //默认构造函数
delete a; //释放单个结构体的空间

4. Integer overflow problem

type name Bytes Ranges
signed char 1 -128~+127
short int 2 -32768~+32767
int 4 -2147483648~+2147483647
long int 4 -2147483648~+2141483647
long long long int 8 -9223372036854775808~+9223372036854775807

The most common one is the int type overflow problem. In the code, some unnecessary integer type overflow can be avoided through skillful handling:

// 取两数中间值
int mid = left + (right - left) / 2;

// 比较多数和与目标值的大小
if (a + b > target - c - d) ;

Data structure related

1. Initialization

Initialization of vector

// 一维数组的初始化
vector<int> v(n);     // 使用n个0来初始化,类似于v.resize(n)

vector<int> v(n, m);  // 使用n个m来初始化,类似于v.resize(n, m)

vector<int> v(v0);    // 使用另外一个数组v0来初始化v

// 二维数组的初始化

vector<vector<int>> v;
v.resize(n, v0);      // 使用n个一维数组v0来初始化

vector<vector<int>> v(3, vector<int>(4, 1));  // 直接使用vector(n, m)来表示v0

2. Add element emplace_back

This function is newly added by C++11, and its function is the same as push_back(), which adds an element at the end of the vector container.
Compared to push_back(),emplace_back() reduces one copy and assignment operation in implementation.
Note: push_back() can also add elements at the end of containers such as string, while emplace_back() is only applied to vector containers.

vector<int> v;
v.emplace_back(1);

3. Insert element insert

insert(p, t);

in iterator pBeforeInsert an element with value t

4. Range assignment fill

fill(array.begin(), array.end(), val);

All elements of an interval are assigned val values.
Assignments cannot be made with resize already initialized:resize does not reinitialize the existing elements of the original vector

Algorithm related

1. Sum accumulate

int accumulate (first address, last address, accumulated initial value);
Note: The last address of the array is the next address of the last element.

#include <numeric>

int sum = accumulate(array.begin(), array.end(), 0);

2. sort sort

void sort (first address, last address, [sorting method]);
when the sorting method is default,The default sorting method is sorting from small to large

#include <algorithm>

// 排序方法缺省
int a[] = {
    
    45, 12, 34, 77, 90, 11, 2, 4, 5, 55};
sort(a, a+10); // 从小到大排序

// 排序方法不缺省
bool cmp(int a,int b){
    
    
	return a>b;
}
int a[] = {
    
    45,12,34,77,90,11,2,4,5,55};
sort(a, a+10, cmp); // 从大到小排序

// 排序方法可以采用多层逻辑,也可以结合数据结构,灵活定义
typedef struct student{
    
    
	char name[20];
	int math;
	int english;
}Student;
bool cmp(Student a, Student b){
    
    
	if(a.math > b.math )
		return a.math < b.math ; // 按math从小到大排序 
	else if(a.math == b.math )
		return a.english > b.english; // math相等,按endlish从大到小排序
}
Student a[4] = {
    
    {
    
    "zhangsan", 67, 89}, {
    
    "lisi", 90, 56},{
    
    "wangwu", 90, 99}};
sort(a, a+3, cmp); // 先按math从小到大排序,math相等,按english从大到小排序 

3. Full arrangement next_permutation

bool next_permutation(first address, last address);
The function generates an arrangement according to the lexicographical order, and it increases sequentially from the current lexicographical order in the array until it reaches the maximum lexicographical order.

#include <algorithm>
int a[3] = {
    
    1, 0, 2};
do
{
    
    
	for(int i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");
}
while(next_permutation(a,a+n));

The output is:
1 0 2
1 2 0
2 0 1
2 1 0

4. Binary search for lower_bound, upper_bound

lower_bound(start address, end address, value to be searched)
upper_bound(start address, end address, value to be searched)

Under the guarantee that the array is not in descending order,
the function lower_bound() performs a binary search on the first closed and then open intervals in first and last, and returnsgreater than or equal toThe first element position of val. If all elements are less than val, return the position of last.(the position of last is out of bounds)
The function upper_bound() returns the upper bound of keywords searched in the front-closed and back-opened intervals, and returnsmore than theval's first element position

5. Find the maximum or minimum value *max_element, *min_element

For vector containers

int maxValue = *max_element(v.begin(),v.end()); // 最大值
int minValue = *min_element(v.begin(),v.end()); // 最小值

For normal arrays

int maxValue = *max_element(a,a+6); // 最大值
int minValue = *min_element(a,a+6); // 最小值

6. Reverse the string strrev, reverse

Use the strrev function in string.h

#include <string.h>

char s[]="hello";
strrev(s);

The strrev function is only valid for character arrays, not for string types.

Use the reverse function in the algorithm

#include <algorithm>

string s = "hello";
reverse(s.begin(),s.end());

The reverse function can also reverse the elements of a vector.

7. Intercept string substring substr

string res = s.substr(1,4); // 从s[1]开始截取4个字符,即s[1]到s[4]

8. Generate random number rand

rand() does not require parameters and returns an arbitrary integer from 0 to the maximum random number. The size of the maximum random number is usually a fixed large integer.
General usage:

int num_99 = rand() % 100; // 生成0~99之间的随机整数
int num_ab = rand() % (b - a + 1) + a; // 生成a~b之间的随机整数 

To generate a decimal between 0 and 1, you can first obtain an integer from 0 to 10, and then divide it by 10 to get a random decimal of tenths.

Brush experience

1. Array

Try more double pointers & sliding windows to reduce time complexity; for
array filling problems, you can expand the size of the array in advance with the filled size, and then use double pointers from back to front to operate, so the time and space complexity can be minimized.

2. Linked list

Double pointer, commonly used in the reverse order of single linked list;
setvirtual head nodedummyHead。

3. Hash table

Use an array when there is less data, and use set and map, unordered_set and unordered_map reasonably when there is more data; it
is often used to find whether there are question types in the collection (addition of two numbers, addition of four numbers, etc.), use set when there is no repetition, and need In case of repetition, use map to count the number of occurrences, etc.;
Recommendation: Hash Table Summary - Code Random Record

4. string

Many string problems can be solved as array problems, especiallyarray filling problem;
The problem of reversing the string: first the part and then the whole: Jianzhi Offer58-II. Left-rotate the string & first the whole and then the part: 151. Flip the words in the string ;
the best understanding of the KMP algorithm that I have read: how to Better understand and master the KMP algorithm? - Ruan Xingzhi's answer- Know almost

5. Stack and Queue

Use double stacks to implement queues (one stack, one stack), and single queues to implement stacks (in-queue loop); priority
queue priority_queue<int>, default large top heap; double-ended queue dequeue;
custom queue & custom Priority Queue Discipline: Sliding Window Maximum , Top K High Frequency Elements

Guess you like

Origin blog.csdn.net/qq_43734019/article/details/119413748