C + + utility functions

Most of them need to add header files #include < cmath > or #include < algorithm >
List of common functions:

swap(nums[i], nums[ptr]); //Exchange function
max(merged.back()[1], R); //Size comparison selection
max_element(myvector.begin(),myvector.end());//Returns the iterator of the largest element in the vector. Note that the iterator is returned and the header file is algorithm
reverse(ans.begin(), ans.end());//Answer reversal
rand Function, C A function used to generate a random number in a language.
sqrt(5); //Root 5
pow(a,2); //Square of a
num = abs(num);//Take the absolute value. abs is for int type
//The distance() function calculates the number of elements in the range represented by the two iterators
rand();  //Returns an arbitrary integer from 0 to the maximum random number
int result = accumulate(nums.begin(), nums.end(), 0);//Sequence summation

reverse function

The function is reverse order (or reverse), which is mostly used for strings, arrays and containers. The header file is #include < algorithm >
The reverse function is used to reverse the order within the range of [first, last] (including the elements pointed to by first, excluding the elements pointed to by last). The reverse function has no return value.
give an example:

string str="hello world , hi";
reverse(str.begin(),str.end());//str result is IH, dlrow olleh
vector<int> v = {5,4,3,2,1};
reverse(v.begin(),v.end());//The value of container v becomes 1,2,3,4,5

max_element() find the maximum value

Header file: #include < algorithm >
Returns the iterator pointing to the maximum value in the [front closed and back open) sequence interval. If the output value is, an asterisk should be added in front of max_element, and the third parameter cmp can be written or not.
max_element() and min_element() is arranged from small to large by default, and then
max_element() outputs the last value, min_element() outputs the first value. If the custom cmp function is arranged from large to small, it will lead to max_element() and min_ The two results of element () are reversed.
It can be used for vector < int > or vector < string >, int arr[4] or string arr[4], or structure vector or structure array.
Usage example:

int a[5] = {0, 3, 9, 4, 5};
int *b;
b = max_element(a, a+5);
cout << *b;
//Also applies to vectors
vector<int> myvector;
vector<int>::iterator it;
it = max_element(myvector.begin(),myvector.end());
cout<<*max_element(myvector.begin(),myvector.end());
//Or write a comparison function as the third parameter
static bool cmp(int& a, int& b)
{
	return abs(a)<abs(b);
}
it = max_element(myvector.begin(),myvector.end(),cmp);	
cout<<*it<<end;

abs() absolute value function

abs function of C language:

#include <stdio.h>
#include <stdlib. h> / / use this header file
//abs is an absolute value for int type
num = abs(num);
//Use labs() for long type
long b=-2;
b = labs(b);
//For float, double type
float d = -4.12;         
//The total significant digits of float are generally 7, for example, 12.34, and the total significant digits are 5
d = fabs(d);

C++ abs can naturally support integer and floating-point numbers, which are defined in the cmath header file, \include <cmath>
[note] math H is the header file of C language. In C + +, use math H is also OK. C + + is compatible with C. However, it is recommended to use #include < cmath >, but this must be declared in the std namespace: using namespace std; The functions and methods of use are almost identical.

distance() calculates the number of elements

The distance() function is defined in the #include < iterator > header file and in the std namespace. It is used to calculate the number of elements contained in the range represented by the two iterators. This function returns the number of elements contained in the [first, last] range.

int num = distance (InputIterator first, InputIterator last);
//Create an empty list container
list<int> mylist;
//Add elements 0 ~ 9 to the empty list container
for (int i = 0; i < 10; i++) {
    mylist.push_back(i);}
//Gets the number of elements contained in the [first,last) range
 cout << "distance() = " << distance(mylist.begin(), mylist.end());
//distance() = 10

INT_MAX/MIN max min integer

Constant int in C + +_ Max and INT_MIN represents the maximum and minimum integers respectively.
Header file #include < clips >
For example, if you want to assign a maximum initial value to a variable, you can do the following:

int indexSum = INT_MAX;

Because int occupies 4 bytes and 32 bits, according to the rules of binary coding, INT_MAX =   2 31 − 1   \ 2^{31}-1\,  231−1
,INT_MIN=   − 2 31   \ -2^{31}\,  −231
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
C + + integer upper and lower limits INT_MAX INT_MIN and its operation

next_permutation() array full permutation

In addition to the functions in the standard c + + library, it can also be implemented in a recursive way_ Permutation() and prev_permutation() function. Their header file is #include < algorithm >.
The function has two formal parameters, one is the address of the first element of the sequence, and the other is the address of the last element of the sequence. The return value is bool type. When the full permutation reaches the last case, it returns false, otherwise it returns true.
Note: use next_ Permutation (first address, last address) the sequence for Full Permutation must start with the smallest dictionary permutation (i.e. from small to large).
prev_permutation() function requires that the original sequence of numbers must be arranged from large to small.
Therefore, these two library functions are generally used in combination with the sort() function
Examples are as follows:

//46. Full arrangement
vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int> > ans;
        sort(nums.begin(),nums.end());//From small to large
        ans.emplace_back(nums);
        while(next_permutation(nums.begin(),nums.end()))
        {
            ans.emplace_back(nums);
        }
        return ans;
    }

If the array int a[] = {3,2,1} arranged from large to small; For full permutation, you need to use while (prev_permutation(a, a+3)).
It should be noted that the full arrangement starts from the next arrangement of the current array, and the current array needs to be output and saved in advance.

The full arrangement is realized by backtracking recursion. The input is nums array and the full arrangement is output:

//46. Full arrangement
void backTrace(vector<vector<int> >& ans, vector<int>& nums, int index, int n)
    {
        // All the numbers have been filled in
        if(index==n)
        {
            ans.emplace_back(nums);
            return ;
        }
        for(int i=index;i<n;++i)
        {
            // Dynamically maintain the array, fill in any number of the current index position and subsequent positions, and exchange them,
            //This allows you to select only the unused numbers on the right at a time
            swap(nums[index],nums[i]);
            // Continue to fill in the next number recursively
            backTrace(ans,nums,index+1,n);
            // Undo the operation, switch back to the current number and prepare to change to the next number
            swap(nums[index],nums[i]);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int> > ans;
        int n = nums.size();
        backTrace(ans, nums, 0, n);
        return ans;
    }

rand() random number function

Header file #include < cstdlib >
1) rand() does not require parameters, it returns an arbitrary integer from 0 to the maximum random number.
The internal implementation of rand() is realized by linear congruence method. It is a pseudo-random number. Due to the long period, it can be regarded as random in a certain range.

2) If you want to generate a random integer from 0 to 99, it can be expressed as: int num = rand()% 100;
If 1 ~ 100 is to be generated, it is as follows: int num = rand()% 100 + 1;

In summary, it can be expressed as: int num = rand()% N + A;
Where a is the starting value, n-1+a is the ending value, and N is the range of integers.

3) Generality: rand ()% (B-A + 1) + A; Represents a random integer between a and B.

4) To generate decimals between 0 and 1, you can first obtain integers from 0 to 10, and then divide them by 10 to obtain 10 random decimals of "random to tenths".
If you want to get random decimals from "random to percentile", you need to get 10 integers from 0 to 100, then divide them by 100, and so on in other cases.

5) Before calling the rand() function, you can use srand() function Set the random number seed. If the random number seed is not set, the random number seed will be automatically designed as 1 when the rand() function is called. If the random seed is the same, the random number generated each time will be the same.

srand() initializes random seed

Is the initialization function of the random number generator. Prototype: void srand(unsigned seed);
Usage: it initializes a random seed and provides a seed corresponding to a random number. If the same seed is used, the following rand() function will appear the same random number, such as srand(1); Use 1 directly to initialize the seed. That is, when the parameter value of srand() is fixed, the number obtained by Rand () is also fixed.
However, in order to prevent the random number from repeating each time, the time function is often used to obtain the system time for initialization. At the same time, the program contains a new header file #include < CTime > to let the random seed come from the system clock.
If you want to generate a random number sequence in a program, you need to set the random seed at most once before generating the random number. That is: just call srand((unsigned)time(NULL)) at the beginning of the main program; Just use rand in the back.
For example:

#include <iostream>
#include <cstdlib> // Header file needed to use srand and rand
#include <ctime> // Header file needed to use time
using namespace std;
void test_rand(void)
     {
           unsigned long n;
          srand((unsigned)time(NULL));
          for(int i = 0; i < 100; i++)
          {
                n = rand();
                printf("d\n", n);
           }
}
Or call time Function must be passed an argument 0:
int main()
{
    unsigned seed;  // Random generator seed
    // Use the time function to get a "seed" value for srand
    seed = time(0);
    srand(seed);
    // Now generate and print three random numbers
    cout << rand() << " " ;
    cout << rand() << " " ;
    cout << rand() << endl;
    return 0;
}

accumulate() accumulation function

Header file #include < numeric >
Adds a number from beginning to end, or performs an operation using a specified operator.
Calculate (first, last, initial value, operation); Four parameters: the starting address of the accumulated element; The end address of the accumulated element and the initial value of the accumulation (usually 0); The fourth parameter is the operation to be performed. It is cumulative by default.
Common summation examples:

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};
    int result = accumulate(nums.begin(), nums.end(), 0);
    cout << result << endl; //result = 15    
    return 0;
}

When summing, accumulate takes three formal parameters: the starting address of the accumulated element; The end address of the accumulated element and the initial value of the accumulation (usually 0).
For example:

int list[10] = { 1,2,3,4,5,6,7,8,9,10 };
sum= accumulate(list, list+10, 0) ; //sum=55

When calculating the continuous product, calculate takes four formal parameters: the starting address of the element of continuous multiplication; The end address of the element of concatenation, the initial value of concatenation (usually 1), and the operation of multiples < int > ()

con_product= accumulate(list, list+3, 1, multiplies<int>()) ;//sum=6

Merge string

 vector<string>a{"1","-2345","+6"};
string a_sum=accumulate(a.begin(), a.end(),string("out: "));//Get out: 1-2345+6

Tower() capital to lowercase

Header file: #include < stdlib h>
Function: returns converted lowercase letters. If no conversion is required, the parameter value will be returned

#include <cstdlib>
int main()
{
    char s[] = "aBcDeFgH12345;!#$";
    printf("before tolower() : %s\n", s);
    //before tolower() : aBcDeFgH12345;!#$
    for(int i = 0; i < sizeof(s); i++)
    {
        s[i] = tolower(s[i]);
    }
    printf("after tolower() : %s\n", s);  
    //after tolower() : abcdefgh12345;!#$   
    return 0;
}

toupper() convert lowercase to uppercase

Convert lowercase letters to uppercase letters.
Declaration of toupper() function:

int toupper(int c);

If c has a corresponding capital letter, the function returns the capital letter of c, otherwise c remains unchanged. The return value is an int value that can be implicitly converted to char type.

The transform(first,last,result,op) operation works on each element

Applies an action to each element of the specified range.
The commonly used overloaded function versions are: transform(first,last,result,op);
Among them, first is the first iterator of the container, last is the last iterator of the container, result is the container where the results are stored, and op is the unary function object to be operated (such as:: tower or:: Tower) or sturct and class.

For example, use the transform function to rewrite the lowercase letters in a given string into uppercase letters, and save the result in an array called second. The content of the original string remains unchanged.

#include <iostream>
#include <algorithm>
using namespace std;
char op(char ch)
{
    if(ch>='A'&&ch<='Z')
        return ch+32;
    else
        return ch;
}
int main()
{
    string first,second;
    cin>>first;
    second.resize(first.size());
    transform(first.begin(),first.end(),second.begin(),op);
    cout<<second<<endl;
    return 0;
}

Of course, you can use existing function objects (such as:: toupper or:: Tower) to simplify and save the results to the str string itself.

string str;  cin>>str;
transform(str.begin(), str.end(), str.begin(), ::toupper);//Capitalize
transform(str.begin(), str.end(), str.begin(), ::tolower);//Convert to lowercase

isalpha() determines whether it is a letter

Header file: #include < ctype h>
Function declaration: int isalpha(int c);
Return value: if c is a letter, the function returns a non-zero value; otherwise, it returns 0.
Usage example:
If str[i] is a letter, it becomes a lowercase letter

	if (isalpha(str[i])) 
    {
        word.push_back(tolower(str[i]));//Convert to lowercase
     } 

isdigit() determines whether to use decimal numbers

Header file: #include < ctype h>
Declaration: int isdigit(int c);
Return value: if c is a number, the function returns a non-zero value; otherwise, it returns 0.

isalnum() determines whether letters or numbers

Check whether the transmitted characters are letters and numbers
Declaration: int isalnum(int c);
Return value: if c is a number or a letter, the function returns a non-zero value; otherwise, it returns 0.

islower() determines whether lowercase letters

Check whether the characters passed are lowercase letters.
Declaration: int islower(int c);
Return value: if c is a lowercase letter, the function returns a non-zero value (true), otherwise it returns 0 (false).

isupper() determines whether capital letters are used

Check whether the characters passed are capital letters
Declaration: int isupper(int c);
Return value: if c is an uppercase letter, the function returns a non-zero value (true), otherwise it returns 0 (false)

Tags: C++ data structure Algorithm leetcode

Posted by Hepp on Mon, 18 Apr 2022 17:06:18 +0930