#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
struct Node {
int x;
int y;
};
bool Cmpare(const Node &a, const Node &b) //const必须加,不然会错,目前不懂为啥。当return的是ture时,a先输出,所以示例中是升序
{
return a.x < b.x;
}
int main()
{
Node a[4]={{1,2},{3,4},{9,10},{5,6}};
sort(a,a+4,Cmpare);
for (int var = 0; var < 4; ++var) {
cout<<a[var].x<<a[var].y<<endl;
}
Node b={7,8};
Node *x= lower_bound(a,a+4,b,Cmpare);
cout<<x->x<<x->y<<endl;
return 0;
}
注释部分也是一种写法
#include <iostream>
using namespace std;
template <typename T>
void DisplayValue(T value)
{
cout<<value<<endl;
}
struct Currency
{
int Dollar;
int Cents;
Currency& operator=(Currency& value)
{
Dollar = value.Dollar;
Cents = value.Cents;
return *this;
}
// bool operator==(const Currency& ps)const{
// if(this->Cents==ps.Cents)
// return true;
// else
// return false;
// }
bool operator<(const Currency& ps)const{
if(this->Cents>ps.Cents)
return true;
else
return false;
}
Currency& operator+(Currency& value)
{
Dollar += value.Dollar;
Cents += value.Cents;
return *this;
}
Currency &operator-(Currency& value)
{
Dollar = Dollar - value.Dollar;
Cents = Cents - value.Cents;
return *this;
}
Currency& operator*(Currency& value)
{
Dollar *= value.Dollar;
Cents *= value.Cents;
return *this;
}
// friend ostream &operator<<(ostream &out,Currency value);
friend ostream& operator<<(ostream &out,Currency value)
{
out<<"The dollar = "<<value.Dollar<<" and The Cents = "<<value.Cents<<endl;
return out;
}
};
bool operator==(const Currency& ps,const Currency& ps2){
if(ps2.Cents==ps.Cents)
return true;
else
return false;
}
//ostream& operator<<(ostream &out,Currency value)
//{
// out<<"The dollar = "<<value.Dollar<<" and The Cents = "<<value.Cents<<endl;
// return out;
//}
int main()
{
Currency c1;
c1.Dollar = 10;
c1.Cents = 5;
Currency c4;
c4.Dollar = 7;
c4.Cents = 6;
if(c1==c4)
cout<<"YES"<<endl;
else
cout<<"No"<<endl;
DisplayValue(c1);
Currency c2,c3;
c2 = c1;
c3= c1+c2;
DisplayValue(c3);
return 0;
}
本文介绍了一个使用C++进行结构体排序的例子,通过自定义比较函数实现sort算法的升序排列,并展示了如何使用模板函数处理不同类型的值。同时,文章还涉及了结构体成员操作符的重载,以及如何在主函数中调用这些功能。
524

被折叠的 条评论
为什么被折叠?



