CMP(C++ sort函式自定義關鍵字函式)

CMP(C++ sort函式自定義關鍵字函式)

比較函式compare()縮寫cmp。

comp

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.The function shall not modify any of its arguments.This can either be a function pointer or a function object.

比較函式,以形參列表中的兩個元素作為參數,並返回可轉換為bool類型的值。 返回的值表示作為第一個參數傳遞的元素是否被認為是在它定義的特定嚴格弱順序中的第二個參數之前。

該函式不得修改其任何參數。

這可以是函式指針或函式對象。

基本介紹

  • 中文名:比較函式
  • 外文名:A comparison functor
  • 參數原型:_Compare __comp
  • 所屬函式:sort
sort函式信息:,實例:,Example:,Output:,

sort函式信息:

std::sort
default (1)
template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

實例:

Example:

// sort algorithm example#include <iostream>     // std::cout#include <algorithm>    // std::sort#include <vector>       // std::vectorbool myfunction (int i,int j) { return (i<j); }struct myclass {  bool operator() (int i,int j) { return (i<j);}} myobject;int main () {  int myints[] = {32,71,12,45,26,80,53,33};  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33  // using default comparison (operator <):  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33  // using function as comp  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)  // using object as comp  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)  // print out content:  std::cout << "myvector contains:";  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)    std::cout << ' ' << *it;  std::cout << '\n';  return 0;}

Output:

myvector contains: 12 26 32 33 45 53 71 80

相關詞條

熱門詞條

聯絡我們