关于vector排序问题,请指教

aiversonwk 2008-10-19 10:01:08
自建得结构体来作为vector得类型时怎么排序呢?结构体有2个以上得值
能说详细点吗?谢谢:)
...全文
172 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
太乙 2008-10-20
  • 打赏
  • 举报
回复
呵呵~~ls正解!
ChamPagneZ 2008-10-20
  • 打赏
  • 举报
回复

//UP
seaboat_wang 2008-10-20
  • 打赏
  • 举报
回复
重载操作符 operater< 以后
调用sort函数
herman~~ 2008-10-19
  • 打赏
  • 举报
回复
结构体重载< 仿函数
星羽 2008-10-19
  • 打赏
  • 举报
回复


#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;

struct st
{
int a;
int b;

st(int _a = 0, int _b = 0) : a(_a), b(_b) {}
st(const st& other) : a(other.a), b(other.b) {}

bool operator < (const st& other)
{
if (a < other.a)
return true;

if (a == other.a)
return b < other.b;

return false;
}
};

int main()
{
vector<st> vst;

vst.push_back(st(1, 2));
vst.push_back(st(3, 2));
vst.push_back(st(1, 3));
vst.push_back(st(5, 7));
vst.push_back(st(7, 4));
vst.push_back(st(2, 3));
vst.push_back(st(2, 8));
vst.push_back(st(8, 1));

for (size_t i = 0; i < vst.size(); ++i)
cout<<"("<<vst[i].a<<", "<<vst[i].b<<")"<<" ";
cout<<endl;

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

cout<<"after sort : "<<endl;
for (size_t i = 0; i < vst.size(); ++i)
cout<<"("<<vst[i].a<<", "<<vst[i].b<<")"<<" ";
cout<<endl;

return 0;
}


-----------


(1, 2) (3, 2) (1, 3) (5, 7) (7, 4) (2, 3) (2, 8) (8, 1)
after sort :
(1, 2) (1, 3) (2, 3) (2, 8) (3, 2) (5, 7) (7, 4) (8, 1)



星羽 2008-10-19
  • 打赏
  • 举报
回复
std::sort
lzr4304061988012 2008-10-19
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 P_T_P 的回复:]
写一个比较函数,或实现operator <.
[/Quote]
up
P_T_P 2008-10-19
  • 打赏
  • 举报
回复
写一个比较函数,或实现operator <.
chlaws 2008-10-19
  • 打赏
  • 举报
回复
sort(vec.begin(),vec.end(),predication);
  • 打赏
  • 举报
回复
你的结构体重载operator<

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧