C++ commonly used STL (container classes, container adapters, iterators and algorithms)

[C++] Detailed explanation of STL

If there are mistakes, please correct me!

What is STL

The STL (Standard Template Library) in C++, the standard template library, is an integral part of the C++ standard library. It provides a rich set of template classes, functions, and algorithms to simplify the implementation of commonly used data structures and algorithms, and improve code reusability and maintainability.

The STL consists of three main components:

  • Containers: Several different types of containers are provided, such as vector, list, map, set, queue, and stack, etc. Each container has its specific functions and performance characteristics to meet different needs.

  • Iterators: Provides a set of common iterator interfaces that can traverse elements in various containers and provide a unified interface for algorithm implementation.

  • Algorithms: Provides a series of general-purpose algorithms, such as sorting, searching, counting, transforming, etc. These algorithms can be applied to various container types and have good performance and readability.

The advantage of STL is that it provides a set of common, efficient, safe, and standard toolsets, making it easier for programmers to implement commonly used data structures and algorithms, and at the same time to write safe, easy-to-read, and efficient code, thus Reduced the difficulty of development and maintenance.

container class

All container classes in C++ STL are as follows:

  1. Sequence Containers:
  • vector: dynamic array, supports random access, and can be dynamically expanded in size.
  • deque: double-ended queue, supports two-way access, and can insert and delete the first and last elements efficiently.
  • list: Doubly linked list, supports sequential access, and can be inserted and deleted efficiently.
  1. Associative Containers:
  • set: An unordered collection based on a red-black tree, with unique elements and arranged in ascending order.
  • multiset: An unordered collection based on a red-black tree. The elements can be repeated and arranged in ascending order.
  • map: An associative array based on a red-black tree, key-value pair storage, and automatic sorting.
  • multimap: An associative array based on a red-black tree. Keys can be repeated, and key-value pairs are stored in the order of insertion.
  1. Unordered Associative Containers:
  • unordered_set: An unordered set based on a hash table, with unique elements, grouped according to the hash value, and the search complexity is O(1).
  • unordered_multiset: An unordered collection based on a hash table, elements can be repeated, grouped by hash value, and the search complexity is O(1).
  • unordered_map: An associative array based on a hash table, key-value pair storage, automatic expansion and reorganization, and a lookup complexity of O(1).
  • unordered_multimap: An associative array based on a hash table, the key can be repeated, the key-value pairs are stored in the order of insertion, and the search complexity is O(1).

container adapter

  • stack is a stack container adapter implemented based on deque or vector or list, and supports last-in-first-out (LIFO) element access. Due to the particularity of the stack, only insert and delete operations are allowed from the top of the stack, so its interface is similar to the vector container, only providing operations such as push, pop, top, etc.
  • queue is a queue container adapter implemented based on deque or list, and supports first-in-first-out (FIFO) element access. Queues require elements to be inserted from the tail and elements to be removed from the head. Therefore, its interface is similar to the deque container, only providing operations such as push, pop, front and back.
  • priority_queue is a heap container adapter implemented based on vector, which supports automatic sorting and efficient insertion and deletion operations. The implementation of heap sort needs to maintain a binary heap, and a priority queue container adapter is provided in C++ STL, which can easily realize the priority queue function. The container adapter is similar to a queue, but each time an element is inserted, the order of the heap is automatically adjusted so that the first element of the queue is always the maximum value (or minimum value).

components

  • pair is a container adapter used to store a pair of values, and can be used to define data structures such as associative arrays and mapping tables. For example, you can use a pair to store a string and an integer, a date and a time, and so on. A pair can be operated using algorithms and containers in STL, such as vector, map, set, etc.
  • heap is part of the heapsort algorithm, it is not a container or a container adapter. Functions such as make_heap, push_heap, and pop_heap are provided in the STL for heap sorting the elements in the container. The make_heap function converts the container into a heap, the push_heap function inserts new elements into the heap, and the pop_heap function removes the top element of the heap and restructures the heap. Use the heap to quickly sort the sequence and find the most value and other operations.

iterator

The iterator in C++ STL can be used to traverse the elements in the container. It is an abstract concept that can traverse various STL containers. Here are all the iterators in C++ STL:

  • Input iterator (Input iterator): The input iterator only supports one-way movement, and can read elements in the container. For example, istream_iterator is an input iterator that reads data from a file or input stream.

  • Output iterator (Output iterator): The output iterator also only supports one-way movement, and can write data into the container. For example, ostream_iterator is an output iterator that writes data to a file or output stream.

  • Forward iterator (Forward iterator): Forward iterator supports one-way movement, can read and modify elements in the container, but cannot traverse the same element repeatedly. For example, both list and forward_list support forward iterators.

  • Bidirectional iterator (Bidirectional iterator): Bidirectional iterator supports bidirectional movement, which can traverse elements forward or backward in the container. For example, deque, set, multiset, map, multimap, etc. support bidirectional iterators.

  • Random access iterator (Random access iterator): Random access iterator supports movement in any direction, can directly access any element in the container, and supports constant-time addition, subtraction, and random access operations. For example, vector, string, and array all support random access iterators.

  • ⭐In addition to the above five iterators, C++ STL also provides some other types of iterators, such as reverse iterators, insert iterators, etc.

In general, iterators in C++ STL are standardized interfaces for traversing elements in containers. They can be easily operated on various containers and provide a variety of different traversal methods.

algorithm (function)

Common Mathematical Functions

The mathematical functions in C++ STL mainly include the following:

  1. Arithmetic operations:
  • plus: addition operation.
  • minus: subtraction operation.
  • multiplies: multiplication operation.
  • divides: division operation.
  • modulus: Modulo operation.
    These arithmetic functions perform element-by-element arithmetic operations on the elements of a container, such as summing, computing an average, and so on.
  1. General mathematical functions:
  • abs: Calculates the absolute value.
  • sqrt: Calculates the square root.
  • pow: calculate power.
  • exp: Calculates the exponential function.
  • log: Calculates the natural logarithm.
  • log10: Computes the base 10 logarithm.
  • ceil: Round up.
  • floor: Round down.
  • round: round up.
  • max: Returns the maximum of two numbers.
  • min: Returns the minimum of two numbers.
    These functions can help programmers to perform various mathematical calculations, such as calculating the square root of a certain number, calculating the power of a certain number, calculating the value of the exponential function of a certain number, and so on.

In addition, STL also provides some other mathematical functions, such as:

  1. Random number generators:
  • rand: Generate pseudo-random numbers.
  • srand: Set the seed of the random number generator, generally use the system time as the seed.
    These functions can help programmers generate random numbers for implementing various random algorithms.

In general, many mathematical functions and arithmetic functions are provided in C++ STL, which can greatly simplify the programmer's development work and improve the maintainability and readability of the code.

Commonly used non-mathematical functions

  • std::find(): Finds an element in the given container and returns an iterator pointing to the first matching element. If no matching element is found, the tail iterator is returned. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
    std::cout << "Found: " << *it << '\n';
}
  • std::count(): Counts the number of times a given value occurs in a container. For example:
std::vector<int> vec {1, 2, 3, 4, 5, 3};
int count = std::count(vec.begin(), vec.end(), 3);
std::cout << "Count of 3: " << count << '\n';
  • std::copy(): Copies data from one container (or iterator range) to another container (or location). For example:
std::vector<int> src {1, 2, 3, 4, 5};
std::vector<int> dest(5);  // 目标容器需要预分配空间
std::copy(src.begin(), src.end(), dest.begin());
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::transform(): Perform some operation on a range of elements and place the result in the target container. For example, the following code doubles the elements in the vec container and stores them in the dest container:
std::vector<int> vec {1, 2, 3, 4, 5};
std::vector<int> dest(vec.size());
std::transform(vec.begin(), vec.end(), dest.begin(),
               [](int i) { return i * 2; });
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::sort(): Sort the elements in the container and support custom comparison functions. For example:
std::vector<int> vec {5, 2, 4, 1, 3};
std::sort(vec.begin(), vec.end());  // 默认从小到大排序
for (auto i : vec) {
    std::cout << i << ' ';
}

other

⭐ Keyword auto (not part of STL)

It can be used closely with STL containers, algorithms, iterators, etc., and can easily deduce information such as elements in the container, algorithm return value, and the type pointed to by the iterator. For example, when using STL containers, you can use auto to define an iterator type:

std::vector<int> vec {1, 2, 3, 4, 5};
for(auto it = vec.begin(); it != vec.end(); ++it) {
    // 使用 auto 推导出迭代器类型为 decltype(vec)::iterator 
    std::cout << *it << " ";
}

Before C++11, if you want to use the iterator of STL container, you need to write lengthy iterator type name, for example:

std::vector<int> vec {1, 2, 3, 4, 5};
for(std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it) {
    // 使用 std::vector<int>::const_iterator 进行迭代
    std::cout << *it << " ";
}

By using the auto keyword, you can make the code more concise, easy to read, and reduce the probability of errors. Therefore, although auto is not part of the STL, it is often used with the auto keyword when using the STL.

some common usage

int a[5] = {1, 3, 5, 7, 9};
for (auto x : a) cout << x;
cout << endl;

vector<int>v(7, 6);
for (auto x : v) cout << x;
cout << endl;

string s = "acdb";
for (auto x : s) cout << x;
cout << endl;

char c[5] = {'b', 'a', 'd', 'c'};
for (auto x : c) cout << x;

//	输出
13579
6666666
acdb
badc





algorithm (function)

Common Mathematical Functions

The mathematical functions in C++ STL mainly include the following:

  1. Arithmetic operations:
  • plus: addition operation.
  • minus: subtraction operation.
  • multiplies: multiplication operation.
  • divides: division operation.
  • modulus: Modulo operation.
    These arithmetic functions perform element-by-element arithmetic operations on the elements of a container, such as summing, computing an average, and so on.
  1. General mathematical functions:
  • abs: Calculates the absolute value.
  • sqrt: Calculates the square root.
  • pow: calculate power.
  • exp: Calculates the exponential function.
  • log: Calculates the natural logarithm.
  • log10: Computes the base 10 logarithm.
  • ceil: Round up.
  • floor: Round down.
  • round: round up.
  • max: Returns the maximum of two numbers.
  • min: Returns the minimum of two numbers.
    These functions can help programmers to perform various mathematical calculations, such as calculating the square root of a certain number, calculating the power of a certain number, calculating the value of the exponential function of a certain number, and so on.

In addition, STL also provides some other mathematical functions, such as:

  1. Random number generators:
  • rand: Generate pseudo-random numbers.
  • srand: Set the seed of the random number generator, generally use the system time as the seed.
    These functions can help programmers generate random numbers for implementing various random algorithms.

In general, many mathematical functions and arithmetic functions are provided in C++ STL, which can greatly simplify the programmer's development work and improve the maintainability and readability of the code.

Commonly used non-mathematical functions

  • std::find(): Finds an element in the given container and returns an iterator pointing to the first matching element. If no matching element is found, the tail iterator is returned. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
    std::cout << "Found: " << *it << '\n';
}
  • std::find_if(): Finds the first element in a given range that satisfies a condition, and returns an iterator of that element. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
auto it = std::find_if(vec.begin(), vec.end(), [](int i) {
    return i % 2 == 0;  // 查找第一个偶数
});
if (it != vec.end()) {
    std::cout << "found: " << *it << '\n';
}
  • std::count(): Counts the number of times a given value occurs in a container. For example:
std::vector<int> vec {1, 2, 3, 4, 5, 3};
int count = std::count(vec.begin(), vec.end(), 3);
std::cout << "Count of 3: " << count << '\n';
  • std::copy(): Copies data from one container (or iterator range) to another container (or location). For example:
std::vector<int> src {1, 2, 3, 4, 5};
std::vector<int> dest(5);  // 目标容器需要预分配空间
std::copy(src.begin(), src.end(), dest.begin());
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::sort(): Sort the elements in the container and support custom comparison functions. For example:
std::vector<int> vec {5, 2, 4, 1, 3};
std::sort(vec.begin(), vec.end());  // 默认从小到大排序
for (auto i : vec) {
    std::cout << i << ' ';
}


bool cmp(int a,int b) {return a>b;}  // 自定义比较函数,从大到小排序
std::vector<int> vec {5, 2, 4, 1, 3};
std::sort(vec.begin(), vec.end(), cmp);
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::nth_element(): Partially sort the elements in a given range so that the elements at the specified position are in the correct position after sorting. Find the kth element in an unordered array in linear time and place it in the correct position where all elements on the left are smaller than this element and all elements on the right are larger than this element. Among them, iter_nth represents the starting position of the interval to be searched, iter_nth + k represents the end position of the interval to be searched, comp is an optional parameter, and specifies a custom comparison function. For example:
std::vector<int> vec {3, 1, 4, 2, 5};
std::nth_element(vec.begin(), vec.begin() + 2, vec.end());  // 将第三个元素放到正确的位置
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::accumulate(): Accumulates the elements in a given range, calculates the sum of a series of values ​​in the interval, and returns the sum. Support for custom start values ​​and binary operation functions. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
int sum = std::accumulate(vec.begin(), vec.end(), 0);  // 从 0 开始累加 
std::cout << "Sum: " << sum << '\n';
  • std::fill(): Assign the specified value to all elements in the container, and any to fill the container. For example:
std::vector<int> vec(5);
std::fill(vec.begin(), vec.end(), 42);
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::memset(): Fill a block of memory , fill binary data by byte, and each byte will be assigned the same value. For example:
std::vector<int> v {1, 2, 3, 4, 5};
std::fill(v.begin(), v.end(), 0);
for (auto i : v) {
    std::cout << i << ' ';
}
  • std::min_element() and std::max_element(): Return iterators to the smallest and largest elements in the given container, respectively. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
auto min_it = std::min_element(vec.begin(), vec.end());
auto max_it = std::max_element(vec.begin(), vec.end());
std::cout << "Min: " << *min_it << ", Max: " << *max_it << '\n';
  • std::lexicographical_compare(): Compare the lexicographical sizes of two containers. For example:
std::vector<int> vec1 {1, 2, 3};
std::vector<int> vec2 {3, 2, 1};
bool result = std::lexicographical_compare(vec1.begin(), vec1.end(),
                                           vec2.begin(), vec2.end());
std::cout << "vec1 < vec2: " << std::boolalpha << result << '\n';
  • std::merge(): Merges two sorted containers into one sorted container. For example:
std::vector<int> vec1 {1, 3, 5};
std::vector<int> vec2 {2, 4, 6};
std::vector<int> dest(vec1.size() + vec2.size());
std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), dest.begin());
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::reverse(): Reverse the elements in the given range. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
std::reverse(vec.begin(), vec.end());
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::reverse_copy(): Copies the elements in the given range into another container and reverses the order of the elements. For example:
std::vector<int> src {1, 2, 3, 4, 5};
std::vector<int> dest(src.size());
std::reverse_copy(src.begin(), src.end(), dest.begin());  // 反转元素顺序并复制到 dest 中
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::unique(): Performs a deduplication operation on adjacent , and returns an iterator pointing to the end of the deduplicated range. It is recommended to sort first and then deduplicate . For example:
std::vector<int> vec {1, 2, 2, 3, 3, 3, 4, 5, 5};
auto it = std::unique(vec.begin(), vec.end());
vec.erase(it, vec.end());  // 删除去重后的冗余元素
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::unique_copy(): Copies the elements in the given range to the target container, and deletes adjacent duplicate elements. For example:
std::vector<int> vec {1, 2, 2, 3, 3, 3, 4, 5, 5};
std::vector<int> dest(vec.size());
auto end_it = std::unique_copy(vec.begin(), vec.end(), dest.begin());
for (auto it = dest.begin(); it != end_it; ++it) {
    std::cout << *it << ' ';
}
  • std::binary_search(): Use the binary search algorithm to find the specified element in the given range, and return whether the search is successful. Note that this function requires that the elements in the range have been sorted in ascending order. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
bool result = std::binary_search(vec.begin(), vec.end(), 3);  // 在 vec 中查找元素 3
std::cout << "found: " << std::boolalpha << result << '\n';
  • std::next_permutation(): Given a permutation, generate the next permutation. Returns false if the current queue is last. Often used for full alignment . For example:
std::vector<int> vec {1, 2, 3};
do {
    for (auto i : vec) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
} while (std::next_permutation(vec.begin(), vec.end()));  // 输出所有排列
  • std::partition(): With the given predicate as the demarcation point, the elements in the container are divided into two parts according to whether the predicate is satisfied or not, and the demarcation iterator is returned. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
auto it = std::partition(vec.begin(), vec.end(), [](int i) {
    return i % 2 == 0;  // 将偶数和奇数分开
});
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::stable_partition(): Similar to std::partition(), but keeps the relative order unchanged. For example:
std::vector<int> vec {1, 2, 3, 4, 5, 6};
std::stable_partition(vec.begin(), vec.end(), [](int i) {
    return i % 2 == 0;  // 将偶数和奇数分开,但保持相对顺序
});
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::partial_sum(): Performs a partial sum operation on the elements in the given range, and puts the result (the sum of the current element and all previous elements) into the destination container. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
std::vector<int> dest(vec.size());
std::partial_sum(vec.begin(), vec.end(), dest.begin());
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::iota(): Incrementally assigns values ​​to elements within a given range. For example:
std::vector<int> vec(5);
std::iota(vec.begin(), vec.end(), 1);
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::rotate(): Rotates the elements within the given range by the specified distance so that the element at the specified position is at the end of the range. It is equivalent to extracting the first few elements and splicing them to the end. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
std::rotate(vec.begin(), vec.begin() + 2, vec.end());  // 将前两个元素移动到最后
for (auto i : vec) {
    std::cout << i << ' ';
}
  • std::adjacent_difference(): Performs a difference operation on adjacent elements in the given range and places the result in the destination container. For example:
std::vector<int> vec {1, 2, 3, 4, 5};
std::vector<int> dest(vec.size());
std::adjacent_difference(vec.begin(), vec.end(), dest.begin());
for (auto i : dest) {
    std::cout << i << ' ';
}
  • std::inner_product(): Calculate the inner product of elements in two ranges and return the result. For example:
std::vector<int> vec1 {1, 2, 3};
std::vector<int> vec2 {4, 5, 6};
int result = std::inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0);  // 对 vec1 和 vec2 中元素进行内积计算
std::cout << "inner product: " << result << '\n';
  • std::clamp(): Clamp the given value within the specified range, and truncate the excess part. For example:
int value = 10;
int result = std::clamp(value, 1, 5);  // 将 value 限制在 [1, 5] 范围内
std::cout << "result: " << result << '\n';

The place below is messy and messy, and it hasn't been sorted out yet.

The place below is messy and messy, and it hasn't been sorted out yet.

The place below is messy and messy, and it hasn't been sorted out yet.

The place below is messy and messy, and it hasn't been sorted out yet.

Common functions

String processing (used a lot)

  • find() finds a string, returns -1 if not found
  • str.replace(pos, len, str)
    replaces, replaces the characters of the specified string with a length of len starting from the starting position pos with str
str=str.replace(str.find("a"),2,"#");  //从第一个a位置开始的两个字符替换成#
str=str.replace(str.begin(),str.begin()+5,"#"); //用#替换从begin位置开始的5个字符
  • substr()
    intercepts the string and returns the string with the subscript from a to b
c=s.substr(a,b)//截取s的下标a开始的b的字符(不足或b不写则到结尾)并赋值给c

string s = "asdfg";
cout << s.substr(1,2) << endl;//此时会输出sd
  • String comparison
    compare(), strcmp()
string s1="asd", s2="asd";
s1.compare(s2);
/*相等返回0, 大于返回1, 小于返回-1*/
char s1[10]="asd", s2[10]="zxc"
strcmp(s1, s2);
/*相等返回0*/
  • String flip
    reverse() function has no return value
string str="asdf";
reverse(str.begin(),str.end());

get string length

string型:s.length(), s.size()
char型:strlen(s),sizeof(str)/sizeof(str[0]),s.length()

  • The length of the string calculated by the strlen() function is an effective length, neither including the terminator '\0' at the end of the string;
  • The length of the string calculated by the length() function does not include the terminator '\0' at the end of the string;
  • The length calculated by the sizeof() operator includes the terminator '\0' at the end of the string;
    when sizeof() is used inside the function to calculate the length of the character array passed in by the formal parameter of the function, the result obtained is the pointer The length corresponds to the number of bytes of the variable, not the length of the string, so be careful here.

get character/string

  • getline : Spaces can be accepted, use string
    getline(cin,s) to get one line of value, remember getchar() to get back the car
string str;
getline(cin,str);
  • getchar() : Accept a character, can receive spaces, carriage returns, only applicable to char, often used to eat carriage returns
  • cin.get : Spaces can be accepted, only applicable to char, get the specified number of characters
char ch[20];
cin.get(ch, 11);//获取10个字符
char ch1;
cin.get(ch1);//获取1个字符,相当于ch1 = cin.get()
  • cin.getline() : Spaces can be accepted, only applicable to char, the usage is similar to cin.get(), to get the specified number of characters
char a[20];
cin.getline(a, 20);

char m[3][20];
for(int i=0;i<3;i++)
	cin.getline(m[i],20);
  • gets() : Receive a string, spaces can be received, only applicable to char
char ch[20];
gets(ch);

Array/container handling

  • lower_bound/upper_bound
    can only operate in ordered arrays or containers! ! !
(lower_bound(a,a+n,int num)-a):在数组a中找到第一个大于等于num的数字并返回其下标

int a[] = {1, 2, 3, 4, 5, 7, 8, 9};
printf("%d", lower_bound(a, a + 8, 6) - a);//-a不能少,因为是地址相减
输出5,a->a+8中第一个大于等于6的位置是5

(upper_bound(a,a+n,int num)-a):在数组a中找到第一个大于num的数字并返回其下标
  • sort()
    //Quick sorting, you can customize the cmp function, and it can also be used for structure sorting
bool compare(int a,int b){
	return a>b;//降序
}
sort(num,num+4,compare);
  • The two functions max_element() and min_element()
    are used to quickly get the maximum/minimum value and the maximum/minimum subscript in the array. The
    application methods of min_element() and max_element() are the same
int num[6]={1,0,5,2,5,0};
cout << *max_element(num,num+6) << endl;
//则此时输出的是num数组的最大值5
cout << max_element(num,num+6)-num << endl;
//则此时输出的是num数组的最大值的下标2
  • unique
    deduplication function
    Note: unique only needs to use sort() to
    sort before using this function. More importantly, the so-called deduplication does not delete duplicate content, but puts They are all at the bottom
unique(data,data+n)//将date数组去重,n是数组长度
  • swap
    exchange
swap(a,b)//a和b进行交换
  • Flip
    the reverse() function has no return value
int num[3]={ 1, 2, 3 };
reverse( num, num+3 );//3是数组长度

vector<int> v = { 1, 2, 3 };
reverse(v.begin(),v.end());

string str="asdf";
reverse(str.begin(),str.end());
  • find ()
    finds a value in the array.
    If find can find it, it returns the subscript address. If it can’t find it, it returns
    the position of the array length i = find (start position, end position + 1, i)
int num[] = {1, 2, 3};
int *index;
index = find(num, num+3, 3);//index是查找到3的所在地址
cout << index-num << endl;//用3所在地址减去数组首元素地址就是3的下标

index = find(num, num+3, 5);//找不到返回数组长度所在地址
cout << index-num << endl;
/*这里输出数组长度3*/

mathematical thought

__gcd()
(Greatest common factor, least common multiple)

To find the greatest common divisor, call the universal header file

int gc = __gcd(4,8);
//如果用不了参考
int gcd(int a,int b){
    if(b==0) return a;
    else
        return gcd(b,a%b);
}

least common multiple

int lcm(int a,int b){
	return a/__gcd(a,b)*b;
}

STL

  • next_permutation()
    full arrangement This is in STL, pay attention to sort the array in ascending order first
//int型数组:
sort(num,num+3);
int num[3] = {5,2,6};
	sort(num,num+3);
	//先使用sort排个序
	do{
		for(int i=0;i<3;i++)
			cout << num[i] << "  ";
		cout << endl;
	}while(next_permutation(num,num+3)); 

//string型: 
string s;
	cin >> s ;
	sort(s.begin(),s.end());
	//先使用sort排个序
	do{
		cout << s << endl;
	}while(next_permutation(s.begin(),s.end())); 

container class

vector, stack, queue, map, pair, heap
vector (vector), double-ended queue (deque), linked list (list), collection (set), multiple collection (multiset), mapping (map) and multiple mapping (multimap)

Some function usages have not been fully remembered.
Use auto or iterator when looping

vector

A container, similar to a dynamic array, but its size can be changed dynamically

Vector is more efficient in obtaining elements and operating on the last element; but for operations on intermediate elements, the performance is relatively poor.

vector<int>v

vector<int >b(a) //将a中的元素复制到b中

vector<int>a(100,6)//定义100个值为6的元素

vector<string>b(a.begin(),a.end()) //将动态数组a的元素值复制到b中

v.begin()//返回指向迭代器第一个元素的指针

v.end()//返回指向迭代器最后一个元素的指针

v.size()//返回当前vector使用数据量的大小

v.empty()//测试vector是否为空

v.front()//返回第一个元素的值

v.back()//返回最后一个元素的值

v.push_back(x)//在容器最后一个位置插入元素x

v.pop_back(x)//删除最后一个元素

//insert erase swap

v.clear()//清空

//Iterators迭代器

vector<int>::iterator iter1;
for (iter1 = v.begin(); iter1 != v.end(); ++iter1) {
        cout << ' ' << *iter1 << endl;   //[0,1,2,3,4,5,6,7,8,9]
}

queue

queue<int> q:建立一个队列q,其内部元素类型是int。

q.push(a):将元素a插入到队列q的末尾。

q.pop():删除队列q的队首元素。

q.front():查询q的队首元素。

q.back():查询q的队尾元素。

q.size():查询q的元素个数。

q.empty():查询q是否为空。

set

set<int>a;

a.insert()//往集合中添加元素,它的参数也是只有一个,就是你想要添加的元素,无返回值。

a.count()//查找出现在集合中的元素的个数,返回值要么是1要么是0
//因为集合的互异性,所以它的返回值要么是1要么是0。
//一般也可以用它来判断某个元素是否在该集合中。

a.begin()和a.end()
//是有返回值的,返回值分别是第一个指向该元素的迭代器和指向最后一个元素迭代器的下一个位置

a.erase()//函数是用来删除指定的元素,参数只有一个,并且是你想要删除的元素,无返回值

a.size()//得出集合中的元素个数。

a.empty()//判断该集合是否为空。 

a.clear()//清空集合中的元素。

stack

stack<int> S;	//定义一个存储整数类型的栈

top()//返回一个栈顶元素的引用,类型为 T&。如果栈为空,返回值未定义。

push(const T& obj)//将对象压入栈顶
//这是通过调用底层容器的 push_back() 函数完成的。

push(T&& obj)//以移动对象的方式将对象压入栈顶。
//这是通过调用底层容器的有右值引用参数的 push_back() 函数完成的。

pop()//弹出栈顶元素。

size()//返回栈中元素的个数。

empty()//在栈中没有元素的情况下返回 true。

emplace()//用传入的参数调用构造函数,在栈顶生成对象。

pair

//The bottom layer is implemented using a structure to store a pair of data

pair<T1, T2> p1;

p1.first = 1;
 
p1.second = 2.5;
 
cout<<p1.first<<' '<<p1.second<<endl;

map

map<typename1, typename2> mp //typename1是键的类型,typename2是值的类型。

//map中的键是唯一的

map<char, int> mp; 
mp['c'] = 20;
cout << mp['c'];	//答案输出20

//map可以使用it->first来访问键,it->second来访问值

//map会以键从小到大的顺序自动排序

find()
map<char, int>::iterator it = mp.find('b');
cout << it->first << " " << it->second;

erase()
mp.erase(it)//it为需要删除的元素的迭代器
mp.erase(key)//key为要删除的映射的键
mp.erase(first, last)//其中,first为需要删除的区间的起始迭代器,last为需要删除的区间末尾迭代器的下一个地址,即为删除左闭右开的区间[first, last)

size()//获得map中映射的对数

clear()//清空map中的所有元素

unordered_map

unordered_map<string, int> umap; //定义

heap

Heap
Complete binary tree, the parent node is not smaller/greater than the child node

make_heap(v.begin(), v.end(), greater<int>());//生成一个小堆,第三个不加就默认最小堆,加greater<int>()则为最大堆

pop_heap(v.begin(), v.end(), greater<int>()); // 将堆的第零个元素与最后一个元素交换

v.pop_back(); // 删除最后位置的元素

list

Implementation using double linked list

Guess you like

Origin blog.csdn.net/weixin_45940369/article/details/131059386
Recommended