关于c++ sort函数的用法

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class sum
{
public:
sum()
{
}
~sum()
{
}
bool cmp(int x,int y)
{
return x > y;
}
void data()
{
vector<int>test;
test.push_back(5);
test.push_back(1);
test.push_back(9);
sort(test.begin(),test.end(),cmp);
cout<<test[0]<<endl;
cout<<test[1]<<endl;
cout<<test[2]<<endl;
}
};
void main()
{
sum a;
a.data();

}
sort第三个参数比较函数,怎样调用其他类的函数?

第1个回答  2014-03-26
根据你的描述,以struct为元素的vector需要排序,直接在结构体重重载小于号就行了。后续插入到vector中的元素就会以重载的方法升序排列。
struct Item
{
int i;
string str;
bool operator<(const Item &other) const
{
if (i < other.i) // i升序
{
return true;
}
else if (i == other.i)
{
if (strcmp(str.c_str(), other.str.c_str()) < 0) //str升序
{
return true;
}
}
return false;
}
};
如上代码可供参考,如果问题解决,请采纳!
第2个回答  2014-03-26
c++泛型库的sort函数不需要cmp指针
sort(test.begin(),test.end()); //就这样就好了追问

是这样的,我只是随便打了一个例子,其实vector里面存了一个结构体,所以我必须写一个比较函数,但是我发现在类里面这样调用时错误的,求它的正确调用方法

追答

那你要把类方法定义成静态的,然后用sum::cmp引用,某些编译器可能要用&(sum::cmp)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class sum
{
public:
sum()
{
}
~sum()
{
}
static bool cmp(int x,int y)  //静态的
{
return x > y;
}
void data()
{
vector<int>test;
test.push_back(5);
test.push_back(1);
test.push_back(9);
sort(test.begin(),test.end(),sum::cmp);   //sum::cmp
cout<<test[0]<<endl;
cout<<test[1]<<endl;
cout<<test[2]<<endl;
}
};
void main()
{
sum a;
a.data();

}

追问

真厉害,再请教一下,为啥它要设置为静态呢

追答

静态成员不依赖于对象存在,它是属于类的,没有实例对象时就有静态成员了
因为非静态成员必须随对象产生,所以用::是无法确定是哪个对象的

本回答被提问者采纳