]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/intrusive/example/doc_map.cpp
1 /////////////////////////////////////////////////////////////////////////////
3 // (C) Copyright Ion Gaztanaga 2015-2015
5 // Distributed under the Boost Software License, Version 1.0.
6 // (See accompanying file LICENSE_1_0.txt or copy at
7 // http://www.boost.org/LICENSE_1_0.txt)
9 // See http://www.boost.org/libs/intrusive for documentation.
11 /////////////////////////////////////////////////////////////////////////////
13 #include <boost/static_assert.hpp>
14 #include <boost/type_traits/is_same.hpp>
15 #include <boost/intrusive/set.hpp>
16 #include <boost/intrusive/unordered_set.hpp>
20 using namespace boost::intrusive
;
22 class MyClass
: public set_base_hook
<>
23 , public unordered_set_base_hook
<>
27 explicit MyClass(int i
) : first(i
){}
30 //key_of_value function object, must:
31 //- be default constructible if the container constructor requires it
32 //- define the key type using "type"
33 //- define an operator() taking "const value_type&" and
34 // returning "type" or "const type &"
35 struct first_int_is_key
39 const type
& operator()(const MyClass
& v
) const
43 //Define omap like ordered and unordered classes
44 typedef set
< MyClass
, key_of_value
<first_int_is_key
> > OrderedMap
;
45 typedef unordered_set
< MyClass
, key_of_value
<first_int_is_key
> > UnorderedMap
;
49 BOOST_STATIC_ASSERT((boost::is_same
< OrderedMap::key_type
, int>::value
));
50 BOOST_STATIC_ASSERT((boost::is_same
<UnorderedMap::key_type
, int>::value
));
52 //Create several MyClass objects, each one with a different value
53 //and insert them into the omap
54 std::vector
<MyClass
> values
;
55 for(int i
= 0; i
< 100; ++i
) values
.push_back(MyClass(i
));
57 //Create ordered/unordered maps and insert values
58 OrderedMap
omap(values
.begin(), values
.end());
59 UnorderedMap::bucket_type buckets
[100];
60 UnorderedMap
umap(values
.begin(), values
.end(), UnorderedMap::bucket_traits(buckets
, 100));
62 //Test each element using the key_type (int)
63 for(int i
= 0; i
!= 100; ++i
){
64 assert(omap
.find(i
) != omap
.end());
65 assert(umap
.find(i
) != umap
.end());
66 assert(omap
.lower_bound(i
) != omap
.end());
67 assert(++omap
.lower_bound(i
) == omap
.upper_bound(i
));
68 assert(omap
.equal_range(i
).first
!= omap
.equal_range(i
).second
);
69 assert(umap
.equal_range(i
).first
!= umap
.equal_range(i
).second
);
72 //Count and erase by key
73 for(int i
= 0; i
!= 100; ++i
){
74 assert(1 == omap
.count(i
));
75 assert(1 == umap
.count(i
));
76 assert(1 == omap
.erase(i
));
77 assert(1 == umap
.erase(i
));