Common function objects in C++

1. The common function objects in the C++STL library are:

1. std::less and std::greater: used to compare the size of two values, where std::less means sorting from small to large (the default sorting method), and std::greater means sorting from large to small. 2. std::plus and std::minus: used to perform addition and subtraction operations. 3. std::multiplies and std::divides: used to perform multiplication and division operations. 4. std::modulus: used to perform modulo operations. 5. std::logical_and, std::logical_or, and std::logical_not: used to perform logical AND, logical OR, and logical NOT operations. 6. std::equal_to, std::not_equal_to, std::greater_equal, and std::less_equal: used to compare the magnitude relationship of two values, representing equality, inequality, greater than or equal to, and less than or equal to, respectively. 7. std::function: Used to encapsulate functions, any callable object (function, function pointer, function object, etc.) can be encapsulated into a callable object.

2. Code example

Example 1: Example of using std::greater

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int main() {
    vector<int> vec = { 1, 3, 5, 2, 4 };

    // 使用 std::sort 算法对 vec 进行排序
    sort(vec.begin(), vec.end(), greater<int>());

    // 输出排序后的结果
    for (int i : vec) {
        cout << i << " ";
    }

    return 0;
}

Example 2: Example of using multiplies

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int main() {
    vector<int> vec1 = { 1, 2, 3, 4 };
    vector<int> vec2 = { 2, 4, 6, 8 };
    vector<int> result(vec1.size());

    // 使用 std::transform 算法对 vec1 和 vec2 进行元素级别的乘法运算
    transform(vec1.begin(), vec1.end(), vec2.begin(), result.begin(), multiplies<int>());

    // 输出运算结果
    for (int i : result) {
        cout << i << " ";
    }

    return 0;
}

result = {2, 8, 18, 32}

Guess you like

Origin blog.csdn.net/hu853712064/article/details/129766853