multi_index_container是c++ boost库中的一个多索引的容器。因工作中用到了,特来测试试用。
#include "stdafx.h"
#include "test.h" #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 std;
using namespace boost;
using namespace boost::multi_index; struct Book{
int id;
int date;
string name;
string author; Book(int id_,
int date_,
string name_,
string author_)
{
id = id_;
date = date_;
name = name_;
author = author_;
}
}; typedef multi_index_container<
Book,
indexed_by<
ordered_unique<member<Book, int, &Book::id> >,
ordered_non_unique<member<Book, int, &Book::date> >,
ordered_non_unique<member<Book, string, &Book::name> >,
ordered_non_unique<member<Book, string, &Book::author> >
> >BookContainer; typedef BookContainer::nth_index<>::type Id_Index;
typedef BookContainer::nth_index<>::type Date_Index;
typedef BookContainer::nth_index<>::type Name_Index;
typedef BookContainer::nth_index<>::type Author_Index; int _tmain(int argc, _TCHAR* argv[])
{
BookContainer con;
con.insert(Book(, , "math book", "jim"));
con.insert(Book(, , "chinese book", "jam"));
con.insert(Book(, , "english book", "roland"));
con.insert(Book(, , "music book", "rose")); Id_Index& id_idx = con.get<>();
for (auto iter = id_idx.begin(); iter != id_idx.end(); iter++)
{
cout << iter->id << " "
<< iter->date << " "
<< iter->name << " "
<< iter->author << endl;
} cout << endl; Date_Index& date_idx = con.get<>();
for (auto iter = date_idx.begin(); iter != date_idx.end(); iter++)
{
cout << iter->id << " "
<< iter->date << " "
<< iter->name << " "
<< iter->author << endl;
} cout << endl; Name_Index& name_idx = con.get<>();
for (auto iter = name_idx.begin(); iter != name_idx.end(); iter++)
{
cout << iter->id << " "
<< iter->date << " "
<< iter->name << " "
<< iter->author << endl;
} cout << endl; Author_Index& author_idx = con.get<>();
for (auto iter = author_idx.begin(); iter != author_idx.end(); iter++)
{
cout << iter->id << " "
<< iter->date << " "
<< iter->name << " "
<< iter->author << endl;
} getchar();
return ;
}
输出:
可以看到以int型为索引的,输出是按照从小到大来排序的。以string为索引的,是按照字母顺序来输出的。