增强文档(http://www.boost.org/doc/libs/1_55_0/doc/html/intrusive.html)指出侵入式容器是为list
(单/双链接),set
和multiset
实现的。
我找不到地图的实现。有没有更深层次的理由,还是只是等待实施?
答案 0 :(得分:6)
这是因为map<Key, Value>
实际上是set<std::pair<Key const, Value>>
,而Boost.Intrusive和Boost.MultiIndex集允许您使用其中一个值成员作为键。换句话说,map
如果find
可以接受可比较的密钥,而不是搜索which has been a long-standing unresolved issue with std::map
and std::set
的整个值,则无需{{1}}:
关联容器查找函数(find,lower_bound,upper_bound, equal_range)只接受key_type的参数,要求用户构造 (隐式地或显式地)key_type的对象来进行查找。 这可能很昂贵,例如构造一个大对象来搜索集合 当比较器函数只查看对象的一个字段时。那里 用户之间的强烈愿望是能够使用其他类型进行搜索 与key_type相当。
答案 1 :(得分:3)
自version 1.59 Boost.Intrusive supports map-like associative containers以来。它比标准的类地图容器更灵活,因为程序员不必定义任何std::pair
类似的结构来定义key_type
和mapped_type
。新的选项key_of_value被添加到侵入式集接口中,用于定义值的哪一部分应被视为key_type以及如何获取它。这样做是为了在使用Boost.Intrusive时简化类似地图的使用。从Boost文档中获取的示例代码:
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/unordered_set.hpp>
#include <vector>
#include <cassert>
using namespace boost::intrusive;
class MyClass : public set_base_hook<>
, public unordered_set_base_hook<>
{
public:
int first;
explicit MyClass(int i) : first(i){}
};
//key_of_value function object, must:
//- be default constructible (and lightweight)
//- define the key type using "type"
//- define an operator() taking "const value_type&" and
// returning "const type &"
struct first_int_is_key
{
typedef int type;
const type & operator()(const MyClass& v) const
{ return v.first; }
};
//Define omap like ordered and unordered classes
typedef set< MyClass, key_of_value<first_int_is_key> > OrderedMap;
typedef unordered_set< MyClass, key_of_value<first_int_is_key> > UnorderedMap;
int main()
{
BOOST_STATIC_ASSERT((boost::is_same< OrderedMap::key_type, int>::value));
BOOST_STATIC_ASSERT((boost::is_same<UnorderedMap::key_type, int>::value));
//Create several MyClass objects, each one with a different value
//and insert them into the omap
std::vector<MyClass> values;
for(int i = 0; i < 100; ++i) values.push_back(MyClass(i));
//Create ordered/unordered maps and insert values
OrderedMap omap(values.begin(), values.end());
UnorderedMap::bucket_type buckets[100];
UnorderedMap umap(values.begin(), values.end(), UnorderedMap::bucket_traits(buckets, 100));
//Test each element using the key_type (int)
for(int i = 0; i != 100; ++i){
assert(omap.find(i) != omap.end());
assert(umap.find(i) != umap.end());
assert(omap.lower_bound(i) != omap.end());
assert(++omap.lower_bound(i) == omap.upper_bound(i));
assert(omap.equal_range(i).first != omap.equal_range(i).second);
assert(umap.equal_range(i).first != umap.equal_range(i).second);
}
//Count and erase by key
for(int i = 0; i != 100; ++i){
assert(1 == omap.count(i));
assert(1 == umap.count(i));
assert(1 == omap.erase(i));
assert(1 == umap.erase(i));
}
assert(omap.empty());
assert(umap.empty());
return 0;
}