Home > Article > Backend Development > What are the commonly used STL function objects in the C++ standard library?
C STL provides a variety of function objects that can be used to compare, sort and operate elements. Common function objects include less for ascending sorting, greater for descending sorting, equal_to for comparing equality, and bind2nd and mem_fn for binding function parameters. In practice, you can sort an array in descending order by using the greater function object, as follows: Using the sort() function, the greater function object will sort the elements in the specified range in descending order.
Commonly used STL function objects in the C standard library
The function object, namely Functor, is a function object that can be called and returned The result object. The C standard library provides many useful STL function objects for use in a variety of algorithms and operations.
The following are some commonly used function objects in C STL:
Practical case:
Use the greater
function object to sort the integer array in descending order:
#include <algorithm> #include <vector> using namespace std; int main() { vector<int> myVector = {1, 3, 5, 2, 4}; // 使用 greater 函数对象对 myVector 中的元素进行降序排序 sort(myVector.begin(), myVector.end(), greater<int>()); // 输出排序后的数组 for (auto it = myVector.begin(); it != myVector.end(); ++it) { cout << *it << " "; } cout << endl; return 0; }
Output:
5 4 3 2 1
The above is the detailed content of What are the commonly used STL function objects in the C++ standard library?. For more information, please follow other related articles on the PHP Chinese website!