linux c++库boost中unordered_set是基于hash的无序集合,只有key没有value。如何插入数据及实现unordered_set的快速查找呢?插入数据使用 insert方法,查找则使用find方法,find方法返回unordered_set的iterator,如果返回为end()表示未查找到,否则表示查找到。
boost库中unordered_set 定义如下:
template <
class Key,
class Hash = boost::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<Key> >
class unordered_set;
下面的代码给出了一个示例:
#include "stdio.h"
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <string>
#include <utility>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
// g++ -o test_unordered test_unordered.cpp -std=c++0x
int main(int argc,char *argv[])
{
unordered_set<string> myset;
unordered_set<string>::iterator it;
for(int i=0;i<100;i++)
{
try
{
myset.insert(lexical_cast<string>(i));
}
catch(bad_lexical_cast &)
{
printf("lexical_cast<string>(i) error!");
}
}
for(int i=90;i<110;i++)
{
try
{
it=myset.find(lexical_cast<string>(i));
printf("%drn",(it==myset.end()));
}
catch(bad_lexical_cast &)
{
printf("lexical_cast<string>(i) error!");
}
}
return 0;
}
再附加一段来自网上的示例代码:
#include <boost/unordered_set.hpp>
#include <boost/assign.hpp>
#include <boost/typeof/typeof.hpp>
using namespace boost;
using namespace std;
template<typename T>
void hash_func()
{
T s = (boost::assign::list_of(1),2,3,4,5); /* 初始化数据 */
for (BOOST_AUTO(p, s.begin()); p != s.end(); ++p)
//for (T::iterator p = s.begin(); p!= s.end(); ++p)
{
cout << *p << " ";
}
cout << endl;
cout << s.size() << endl;
s.clear();
cout << s.empty() << endl;
s.insert(8);
s.insert(45);
cout << s.size() << endl;
cout << *s.find(8) << endl;
s.erase(45);
}
int main(void)
{
//hash_func<ext::hash_set<int> >(); /* stlport的hash_set 偶没安装 */
hash_func<unordered_set<int> >();
}