multi_index_container

根据不同的类中不同的字段排序


#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <iostream>
#include <string.h>

using namespace boost;
using namespace std;

struct Student
{
Student(int i,string n,int a)
{
id = i;
name = n;
age = a;
}
friend std::ostream& operator<<(std::ostream& os,const Student& a)
{
os << "id:" << a.id << ",name:" << a.name << ",age:"<<a.age << std::endl;
return os;
}
int id;
string name;
int age;
};

typedef boost::multi_index_container<Student,boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<Student,int,&Student::id>>,//id唯一
boost::multi_index::ordered_unique<boost::multi_index::member<Student,string,&Student::name>>,
boost::multi_index::ordered_non_unique<boost::multi_index::member<Student,int,&Student::age>>//age允许不唯一
>
> StudentContainer;

typedef StudentContainer::nth_index<0>::type IdIndex;
typedef StudentContainer::nth_index<1>::type NameIndex;
typedef StudentContainer::nth_index<2>::type AgeIndex;

int main()
{
StudentContainer sc;
sc.insert(Student(1,"zhangsan",20));
sc.insert(Student(3,"lisi",22));
sc.insert(Student(2,"wangwu",21));
sc.insert(Student(4,"zhaoliu",22));

IdIndex& sortById = sc.get<0>();
NameIndex& sortByName = sc.get<1>();
AgeIndex& sortByAge = sc.get<2>();

cout << "sort by id:" << endl;
copy(sortById.begin(),sortById.end(), ostream_iterator<Student>(cout));

cout << "sort by name:" << endl;
copy(sortByName.begin(),sortByName.end(), ostream_iterator<Student>(cout));

cout << "sort by age:" << endl;
copy(sortByAge.begin(),sortByAge.end(), ostream_iterator<Student>(cout));

}


sort by id:
id:1,name:zhangsan,age:20
id:2,name:wangwu,age:21
id:3,name:lisi,age:22
id:4,name:zhaoliu,age:22
sort by name:
id:3,name:lisi,age:22
id:2,name:wangwu,age:21
id:1,name:zhangsan,age:20
id:4,name:zhaoliu,age:22
sort by age:
id:1,name:zhangsan,age:20
id:2,name:wangwu,age:21
id:3,name:lisi,age:22
id:4,name:zhaoliu,age:22


account_object.hpp 320,371
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值