Boost练习程序(multi_index_container)

时间:2023-03-09 02:53:31
Boost练习程序(multi_index_container)

代码来自:http://blog.csdn.net/whuqin/article/details/8482547

该容器能实现多列索引,挺好。

#include <string>
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp> using namespace boost;
using namespace boost::multi_index;
using namespace std;
struct Employee{
int id;
string name;
int age; Employee(int id_,string name_,int age_):id(id_),name(name_),age(age_){} friend ostream& operator<<(ostream& os,const Employee& e)
{
os<<e.id<<" "<<e.name<<" "<<e.age<<endl;
return os;
}
}; typedef multi_index_container<
Employee,
indexed_by<
ordered_unique<member<Employee, int, &Employee::id> >,
ordered_non_unique<member<Employee, string, &Employee::name> >,
ordered_non_unique<member<Employee, int, &Employee::age> >
>
> EmployeeContainer; typedef EmployeeContainer::nth_index<>::type IdIndex;
typedef EmployeeContainer::nth_index<>::type NameIndex;
typedef EmployeeContainer::nth_index<>::type AgeIndex; int main(){
EmployeeContainer con;
con.insert(Employee(,"Joe",));
con.insert(Employee(,"Robert",));
con.insert(Employee(,"John",)); IdIndex& ids = con.get<>();
copy(ids.begin(),ids.end(), ostream_iterator<Employee>(cout));
cout << endl; NameIndex& names = con.get<>();
copy(names.begin(), names.end(), ostream_iterator<Employee>(cout));
cout << endl; // names.erase(names.begin()); AgeIndex& ages = con.get<>();
copy(ages.begin(), ages.end(), ostream_iterator<Employee>(cout));
cout << endl; return ;
}