64,282
社区成员
发帖
与我相关
我的任务
分享
#include <list>
#include <algorithm>
#include <string>
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <functional>
#include <set>
#include <vector>
#include <iterator>
using namespace std;
class A{
public:
int id;
double energy;
bool operator> (const A& a) const{
return this->energy > a.energy;
}
friend ostream& operator<< (ostream& ct, const A& a)
{
ct << a.id << " " << a.energy << endl;
return ct;
}
};
class B{
public:
set<A> _l2;
};
int main(){
B b;
for(int i = 0; i < 10; i++) {
A a;
a.id = i;
a.energy = rand() % 10;
b._l2.insert(a);
}
copy(b._l2.begin(), b._l2.end(), ostream_iterator<A>(cout, ""));
cout << endl;
vector<A>v(b._l2.begin(), b._l2.end());//拷贝到vector
// copy(v.begin(), v.end(), ostream_iterator<A>(cout, ""));
// cout << endl;
sort(v.begin(), v.end(), greater<A>());//降序排序
copy(v.begin(), v.end(), ostream_iterator<A>(cout, ""));
cout << endl;
copy(v.begin(), v.end(), inserter(b._l2, b._l2.end()));//拷贝到set
copy(b._l2.begin(), b._l2.end(), ostream_iterator<A>(cout, ""));
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
//for_each 的谓词,为了输出不同的对象, 这里利用了函数对象
template<class T>
class Display: public binary_function<T, T,bool>
{
public:
void operator()(const T& a)
{
cout<<a<<endl;
}
};
class A //待排序的类
{
public:
A(int i,int j): m_i(i),m_j(j){}
friend ostream& operator<<(ostream& out, const A& a)
{
out<< a.m_i << " " << a.m_j << endl;
return out;
}
bool operator> (const A& a)const
{
return this->m_j > a.m_j;
}
private:
int m_i;
double m_j;
};
template<class T>
class Greater: public binary_function<T, T,bool>
{
public:
bool operator()(const T& a, const T& b)
{
return a > b;
}
};
int main()
{
vector<A> Avec;
A a1(3,5);
A a2(8,3);
A a3(2,4.3);
A a4(6,8);
Avec.push_back(a1);
Avec.push_back(a2);
Avec.push_back(a3);
Avec.push_back(a4);
// sort(Avec.begin(), Avec.end(),Greater<A>());//自己的Greater函数
sort(Avec.begin(), Avec.end(), greater<A>());//系统的greater函数
for_each(Avec.begin(), Avec.end(), Display<A>());//输出降序排列对象容器
return 0;
}
class B{
public:
set<A,std::greater<A>> _l2;
};