注册 登录
编程论坛 C++教室

[求助]stl sort中的谓词参数

aipb2007 发布于 2007-10-14 12:34, 1136 次点击

sort中第三个参数是个函数指针,返回类型bool,接受两个元素对象。

我想知道其完整的定义类型

bool (*pred) (****,****);

4 回复
#2
HJin2007-10-14 13:02
回复:(aipb2007)[求助]stl sort中的谓词参数

don't know if i understand what you need.

The predicate (I don't know if it should be translated as "weici") can be a funtion pointer and function object --- a class which overloads operator().


Here is what I copied from cplusplus.com


程序代码:

// sort algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;


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};
  vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33
  vector<int>::iterator it;


  // using default comparison (operator <):
  sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33


  // using function as comp
  sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)


  // using object as comp
  sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)


  // print out content:
  cout << \"myvector contains:\";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout << \" \" << *it;


  cout << endl;


  return 0;
}


#3
aipb20072007-10-14 15:02

oh,I made a unclear expression.

my problem is:

template<class T>
struct X{
typedef bool (*pred)(const T&,const T&); //define a function pointer type
pred p; //pred data member
X(pred _p):p(_p){}
};
bool cmp1(int a,int b){return a<b;}
bool cmp2(const int &a,const int &b){return a<b;}
X<int> x1(cmp1); //doesn't work,compile error
X<int> x2(cmp2); //ok


how I define the type of pred can accept both cmp1 and cmp2?
or maybe I should use the sort(1,2,pred)'s way to implement,because both sort(..,..,cmp1) and sort(..,..,cmp2)
can be accepted,but I don't konw the sort's implementation clearly.

[此贴子已经被作者于2007-10-14 15:19:17编辑过]

#4
jiangzw6252007-10-19 21:43

why don't you refer stl source code?

#5
孤魂居士2007-10-19 22:16
我进入了外语世界
1