首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用object作为比较定义的C++ <algorithm> <algorithm>()

使用object作为比较定义的C++ <algorithm> <algorithm>()
EN

Stack Overflow用户
提问于 2020-01-12 06:34:31
回答 1查看 63关注 0票数 0

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

我正在阅读这里的参考资料,这让我有点迷惑。在std::sort (myvector.begin(), myvector.end(), myobject)行中使用myobject进行排序是如何工作的?另外,bool operator() (int i,int j) { return (i<j)是如何过载的呢?我不明白()是如何重载的,但我可以看出这与myobject的使用方式有关。

代码语言:javascript
复制
    // 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;
}
EN

回答 1

Stack Overflow用户

发布于 2020-01-12 06:48:40

我不明白()是怎么重载的

我想这没什么好理解的。它只是一个成员方法,名字很奇怪(声明/定义中的operator()),调用方式也很奇怪(object()而不是object.ordinary_method())。这只是语法上的糖,没有黑魔法。

该对象充当传递函数的一种代理。在lambda成为语言的一部分之前,直接传递函数是相当麻烦的。传递structclass要容易得多。带有operator()的结构可以像使用函数一样使用。另外,对象可以存储一些数据,这有时是很方便的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59699239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档