Home  >  Article  >  Backend Development  >  What are the commonly used STL function objects in the C++ standard library?

What are the commonly used STL function objects in the C++ standard library?

王林
王林Original
2024-04-25 13:06:02432browse

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.

C++ 标准库中有哪些常用的 STL 函数对象?

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:

  • less: Comparison function used to sort elements (ascending order ).
  • greater: Comparison function used to sort elements (descending order).
  • equal_to: Equal comparison function, used to check whether two elements are equal.
  • not_equal_to: Not equal to comparison function, used to check whether two elements are not equal.
  • greater_equal: Greater than or equal to comparison function, used to check whether an element is greater than or equal to another element.
  • less_equal: Less than or equal to comparison function, used to check whether one element is less than or equal to another element.
  • bind2nd: Binds a parameter of the function object and returns the bound function object.
  • mem_fn: Creates a function object that creates a function object from a member function pointer.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn