#include<stdio.h>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;

typedef struct rect
{
string name;
int id;
int length;
int width;

//对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序。
bool operator< (const rect &a) const
{
if(id!=a.id)
return id<a.id;
else
{
if(length!=a.length)
return length<a.length;
else
return width<a.width;
}
}
}Rect;

int main()
{
vector<Rect> vec;
Rect rect;

rect.name="jeff";
rect.id=4;
rect.length=7;
rect.width=8;
vec.push_back(rect);



rect.name="li";
rect.id=4;
rect.length=5;
rect.width=6;
vec.push_back(rect);

rect.name="zhang";
rect.id=1;
rect.length=2;
rect.width=3;
vec.push_back(rect);

rect.name="wang";
rect.id=4;
rect.length=7;
rect.width=8;
vec.push_back(rect);

cout << "排序前"<<endl;
for(auto it=vec.begin(); it != vec.end(); it++){
cout<<(*it).name<<' '<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;
}

sort(vec.begin(),vec.end());

cout << "排序后"<<endl;
for(auto it=vec.begin(); it != vec.end(); it++){
cout<<(*it).name<<' '<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;
}





return 0;

}

C++ std::vector 自定义排序_ios