日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++ sort比較函數的寫法,最全面的總結

作者:OpenSani 更新時間: 2022-09-25 編程語言

刷題的時候經常會遇到需要自己寫一個sort比較函數,如果不知道怎么寫比較函數那就算你知道其中的算法邏輯也做不出題目,下面介紹一下幾種自定義的比較方法。

前置條件

  1. 注意C++sort是在algorithm這個包里的,注意include這個包
  2. sort的形式如下:注意只能對RandomAccessIterator 進行排序!!什么是RandomAccessIterator ?如果需要詳細的解釋參看:RandomAccessIterator cppreference,簡單說就是能夠以任意的偏移進行訪問的迭代器!如果不支持這樣的是不能夠用sort進行排序的!

Random-access iterators are iterators that can be used to access elements at an arbitrary offset position relative to the element they point to, offering the same functionality as pointers.

  1. 舉個例子,map里面的迭代器是Bidirectional iterators,只能支持迭代器++,–不支持+n這樣的任意偏移,就不能夠使用sort進行排序

  2. vector, deque支持RandomAccessIterator ,list, map, multimap, set and multiset只bidirectional iterators!

用法

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);

也就是有兩種,一種是采用不寫比較函數,另外一種是自定義比較函數。
注意:無論哪種前兩個參數都是RandomAccessIterator,也就是不能直接傳變量進去,必須是傳入相應的迭代器,這是新手一開始非常容易犯的錯誤。

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.

第1種直接寫比較函數

bool myfunction (int i,int j) { return (i<j); }

注意:這種比較函數必須寫在類外部(全局區域)或聲明為靜態函數!(我聽說是因為如果是作為一個成員函數,默認擁有一個this指針,和sort函數需要的函數對象類型不一樣)。

第2種定義一個結構體,構造一個函數對象(function object)也就是對運算符()進行重載,這就是相當于構造了一個函數對象

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

第3種采用lambada函數

對于簡單的函數比較,可以采用C++11的新特性lambada函數

sort(msVector.begin(), msVector.end(), [](const MyStruct& ms1, const MyStruct& ms2){
    return ms1.weight < ms2.weight;
});

可以參考:https://www.cnblogs.com/DswCnblog/p/5629165.html

第4種采用默認的less和greater

其實less和greater都是函數對象,即Function object,什么是function object?

Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a function call.

可以看一下less的模板:

template <class T> struct less {
  bool operator() (const T& x, const T& y) const {return x<y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};

可以看出來實際上less也是重載了一個()運算符,注意less是表示第一個元素比第二個元素小,其實就是升序排列。
舉例:

// less example
#include <iostream>     // std::cout
#include <functional>   // std::less
#include <algorithm>    // std::sort, std::includes

int main () {
  int foo[]={10,20,5,15,25};
  int bar[]={15,10,20};
  std::sort (foo, foo+5, std::less<int>());  // 5 10 15 20 25
  std::sort (bar, bar+3, std::less<int>());  //   10 15 20
  if (std::includes (foo, foo+5, bar, bar+3, std::less<int>()))
    std::cout << "foo includes bar.\n";
  return 0;
}

同樣的,greater就表示降序排列,這是他的模板和應用示例。
模板:

template <class T> struct greater {
  bool operator() (const T& x, const T& y) const {return x>y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};

示例:

// greater example
#include <iostream>     // std::cout
#include <functional>   // std::greater
#include <algorithm>    // std::sort

int main () {
  int numbers[]={20,40,50,10,30};
  std::sort (numbers, numbers+5, std::greater<int>());
  for (int i=0; i<5; i++)
    std::cout << numbers[i] << ' ';
  std::cout << '\n';
  return 0;
}

我個人建議還是采用第一種和第二種,第四種的方法,相對直觀,如果還有其他方法也歡迎討論。

原文鏈接:https://blog.csdn.net/Sansipi/article/details/127019948

欄目分類
最近更新