multi_index_container 多索引容器

multi_index_container是c++ boost库中的一个多索引的容器。因工作中用到了,特来测试试用。

 1 #include "stdafx.h"
 2 #include "test.h"
 3 
 4 #include <string>
 5 #include <iostream>
 6 #include <boost/multi_index_container.hpp>
 7 #include <boost/multi_index/member.hpp>
 8 #include <boost/multi_index/ordered_index.hpp>
 9 
10 using namespace std;
11 using namespace boost;
12 using namespace boost::multi_index;
13 
14 struct Book{
15     int id;
16     int date;
17     string name;
18     string author;
19 
20     Book(int id_,
21          int date_,
22          string name_,
23          string author_)
24     {
25         id = id_;
26         date = date_;
27         name = name_;
28         author = author_;
29     }
30 };
31 
32 typedef multi_index_container<
33     Book,
34     indexed_by<
35     ordered_unique<member<Book, int, &Book::id> >,
36     ordered_non_unique<member<Book, int, &Book::date> >,
37     ordered_non_unique<member<Book, string, &Book::name> >,
38     ordered_non_unique<member<Book, string, &Book::author> >
39     > >BookContainer;
40 
41 typedef BookContainer::nth_index<0>::type Id_Index;
42 typedef BookContainer::nth_index<1>::type Date_Index;
43 typedef BookContainer::nth_index<2>::type Name_Index;
44 typedef BookContainer::nth_index<3>::type Author_Index;
45 
46 int _tmain(int argc, _TCHAR* argv[])
47 {
48     BookContainer con;
49     con.insert(Book(0, 2011, "math book", "jim"));
50     con.insert(Book(2, 2008, "chinese book", "jam"));
51     con.insert(Book(1, 2005, "english book", "roland"));
52     con.insert(Book(3, 2010, "music book", "rose"));
53 
54     Id_Index& id_idx = con.get<0>();
55     for (auto iter = id_idx.begin(); iter != id_idx.end(); iter++)
56     {
57         cout << iter->id << "  "
58             << iter->date << "  "
59             << iter->name << "  "
60             << iter->author << endl;
61     }
62 
63     cout << endl;
64 
65     Date_Index& date_idx = con.get<1>();
66     for (auto iter = date_idx.begin(); iter != date_idx.end(); iter++)
67     {
68         cout << iter->id << "  "
69             << iter->date << "  "
70             << iter->name << "  "
71             << iter->author << endl;
72     }
73 
74     cout << endl;
75 
76     Name_Index& name_idx = con.get<2>();
77     for (auto iter = name_idx.begin(); iter != name_idx.end(); iter++)
78     {
79         cout << iter->id << "  "
80             << iter->date << "  "
81             << iter->name << "  "
82             << iter->author << endl;
83     }
84 
85     cout << endl;
86 
87     Author_Index& author_idx = con.get<3>();
88     for (auto iter = author_idx.begin(); iter != author_idx.end(); iter++)
89     {
90         cout << iter->id << "  "
91             << iter->date << "  "
92             << iter->name << "  "
93             << iter->author << endl;
94     }
95 
96     getchar();
97     return 0;
98 }

输出:

可以看到以int型为索引的,输出是按照从小到大来排序的。以string为索引的,是按照字母顺序来输出的。

原文地址:https://www.cnblogs.com/tyche116/p/9205362.html