昨天编译,安装好了boost,今天想小试一把。以前看了些书,都说STL里面缺少了hash,而boost::hash也基本确定进入C++0X的标准了,何不试一下boot::hash呢?浏览了一下boost::hash的document,感觉不太难,试试了。现在Dev-CPP中设置好include和lib的路径,代码如下(贴代码凑文章了,呵呵):
#include <iostream>
#include <boost/functional/hash.hpp>
using namespace std;
using namespace boost;
class X {
public:
X(int i): val_(i) {}
int get_val() const { return val_; }
private:
int val_;
};
//construct a hash function for class X
size_t hash_value(const X &x)
{
boost::hash<int> hasher;
return hasher(x.get_val());
}
int main(int argc, char *argv[])
{
boost::hash<std::string> string_hash;
hash<double> double_hash;
hash<vector<int> > vector_hash;
//hash for user defined type
hash<X> customerX_hash;
vector<int> v;
X x(32);
size_t h = string_hash("hash me");
cout << h << "/n";
h = double_hash(3.1415927);
cout << h << "/n";
h = vector_hash(v);
cout << h << "/n";
v.push_back(10);
h = vector_hash(v);
cout << h << "/n";
h = customerX_hash(x);
cout << h << "/n";
system("PAUSE");
return 0;
}
怎么样,简单吧?标准的,扩展自定义的类型,都有了。
继续努力学习中。。。
#include <iostream>
#include <boost/functional/hash.hpp>
using namespace std;
using namespace boost;
class X {
public:
X(int i): val_(i) {}
int get_val() const { return val_; }
private:
int val_;
};
//construct a hash function for class X
size_t hash_value(const X &x)
{
boost::hash<int> hasher;
return hasher(x.get_val());
}
int main(int argc, char *argv[])
{
boost::hash<std::string> string_hash;
hash<double> double_hash;
hash<vector<int> > vector_hash;
//hash for user defined type
hash<X> customerX_hash;
vector<int> v;
X x(32);
size_t h = string_hash("hash me");
cout << h << "/n";
h = double_hash(3.1415927);
cout << h << "/n";
h = vector_hash(v);
cout << h << "/n";
v.push_back(10);
h = vector_hash(v);
cout << h << "/n";
h = customerX_hash(x);
cout << h << "/n";
system("PAUSE");
return 0;
}
怎么样,简单吧?标准的,扩展自定义的类型,都有了。
继续努力学习中。。。
本文通过一个简单的实例展示了如何使用Boost库中的hash功能。作者在Dev-CPP环境中配置了必要的路径,并编写了一个程序来演示如何为不同类型的对象(如字符串、双精度浮点数、整数向量及自定义类型)生成哈希值。
1516

被折叠的 条评论
为什么被折叠?



