Ticket #7927: multiindex.c++

File multiindex.c++, 2.7 KB (added by jdy@…, 10 years ago)

sample code showing multi_index working with interprocess

Line 
1
2#include<iostream>
3#include<utility>
4#include<functional>
5
6#include <boost/interprocess/allocators/allocator.hpp>
7#include <boost/interprocess/managed_mapped_file.hpp>
8
9#include <boost/multi_index_container.hpp>
10#include <boost/multi_index/ordered_index.hpp>
11#include <boost/multi_index/member.hpp>
12
13struct from{};
14struct to{};
15
16//using boost::multi_index_countainer;
17//using namespace boost::multi_index;
18
19int main(int argc, char** argv) {
20
21 typedef int key_t;
22 typedef int pay_t;
23
24 typedef typename std::pair<key_t, pay_t> val_t;
25
26 typedef boost::interprocess::managed_mapped_file segment_t;
27 typedef segment_t::segment_manager segment_manager_t;
28
29 typedef boost::interprocess::allocator< val_t, segment_manager_t> allocator_t;
30
31 typedef boost::multi_index_container<
32 val_t,
33 boost::multi_index::indexed_by<
34 boost::multi_index::ordered_unique<
35 boost::multi_index::tag<from>,
36 boost::multi_index::member<val_t, key_t, &val_t::first>
37 >,
38 boost::multi_index::ordered_unique<
39 boost::multi_index::tag<to>,
40 boost::multi_index::member<val_t, pay_t, &val_t::second>
41 >
42 >,
43 allocator_t
44 > map_t;
45
46 {
47 std::cout << "Writing" << std::endl;
48 segment_t segment(boost::interprocess::open_or_create,"scratch.multiindex",10000);
49 allocator_t allocator(segment.get_segment_manager());
50
51 map_t* map = segment.find_or_construct<map_t>("multiindex")(allocator);
52
53 std::cout << "There were " << map->size() << " relations" << std::endl;
54 for( map_t::const_iterator iter = map->begin(); iter != map->end(); ++iter ) {
55 std::cout << iter->first << " <--> " << iter->second << std::endl;
56 }
57
58 map->insert( map_t::value_type(1, 'z' ) );
59 map->insert( map_t::value_type(2, 'Z' ) );
60
61 std::cout << "There are " << map->size() << " relations" << std::endl;
62 for( map_t::const_iterator iter = map->begin(), iend = map->end();
63 iter != iend; ++iter ) {
64 std::cout << iter->first << " <--> " << iter->second << std::endl;
65 }
66 }
67
68 {
69 std::cout << "Reading" << std::endl;
70 segment_t* segment = new segment_t(boost::interprocess::open_read_only,"scratch.multiindex");
71 allocator_t* allocator = new allocator_t(segment->get_segment_manager());
72
73 map_t* map = segment->find<map_t>("multiindex").first;
74
75 std::cout << "There were " << map->size() << " relations" << std::endl;
76 for( map_t::const_iterator iter = map->begin(); iter != map->end(); ++iter ) {
77 std::cout << iter->first << " <--> " << iter->second << std::endl;
78 }
79
80 delete allocator;
81 delete segment;
82 }
83
84 // segment_t::shrink_to_fit("scratch.multiindex");
85 return 0;
86}