C ++ 使用对象作为比较定义的sort()

问题描述 投票:0回答:1

http://www.cplusplus.com/reference/algorithm/sort/

我在这里阅读此参考资料,这使我感到困惑。在行myobject中如何使用std::sort (myvector.begin(), myvector.end(), myobject)进行排序?还有bool operator() (int i,int j) { return (i<j)如何过载?我不了解()如何重载,但是我可以看到它与myobject的使用方式有关。

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

bool 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 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;
}
c++ algorithm sorting overloading operator-keyword
1个回答
0
投票
我不明白()如何重载
© www.soinside.com 2019 - 2024. All rights reserved.