我正在尝试使用Boost's intrusive hashtable并编写一些代码,我可以实例化一个表并在其中插入元素:
#include <iostream>
#include <boost/array.hpp>
#include <boost/intrusive/hashtable.hpp>
using namespace std;
using namespace boost::intrusive;
class MyClass : public unordered_set_base_hook<>
{
public:
MyClass():
mId(0)
{};
int GetId(void) const { return mId; }
void SetId(int id) { mId = id; }
private:
int mId;
};
size_t hash_value(MyClass const& b)
{
boost::hash<int> hasher;
return hasher(b.GetId());
}
bool operator==(MyClass const& a, MyClass const& b)
{
return a.GetId() == b.GetId();
}
static const int ITEM_COUNT = 10;
int main()
{
/* Hash table */
hashtable<MyClass>::bucket_type base_buckets[ITEM_COUNT];
hashtable<MyClass> htable(hashtable<MyClass>::bucket_traits(base_buckets, ITEM_COUNT));
/* Element pool */
boost::array<MyClass,ITEM_COUNT> items;
boost::array<MyClass,ITEM_COUNT>::iterator it;
/* Insert some elements */
int i = 0;
for(it = items.begin(); it != items.end(); ++it)
{
(*it).SetId(i++);
htable.insert_equal(*it);
}
cout<<htable.size()<<" items in table"<<endl;
/* Erase element directly */
i = 5;
cout<<"Erasing item #"<<i<<endl;
htable.erase(items[i]);
cout<<htable.size()<<" items in table"<<endl;
/* Erase by key */
// Todo: Erase by key...
cout<<htable.size()<<" items in table"<<endl;
htable.clear();
return 0;
}
现在,我想要remove elements by key:
template<typename KeyType, typename KeyHasher, typename KeyValueEqual>
size_type erase(const KeyType & key, KeyHasher hash_func,
KeyValueEqual equal_func);
有没有人有如何使用此方法的示例? Boost文档没有哈希表的任何示例,我只涉及模板。看起来我需要实现 hash_func 和 equal_func 。
修改
我猜测了如何实现 hash_func 和 equal_func 。我很幸运,它很有效。我假设这些函数在Boost文档中的某处定义了原型。谁知道这是哪里?