hash function for std::vector<int> needed

M

Markus Dehmann

Hi,

I'd like to hash std::vector<int> objects using hash_set, but I'm not
sure what hash function to use. Does anybody have a suggestion?

Thank you!
Markus
 
A

alan

Hi,

I'd like to hash std::vector<int> objects using hash_set, but I'm not
sure what hash function to use. Does anybody have a suggestion?

Thank you!
Markus

Possibly you can use boost::hash_combine<int> across the vector
(warning, unchecked):
std::size_t vectorhash(std::vector<int> f){
size_t seed = 0;
for_each(f.start(), f.end(), boost::bind(hash_combine<int>, seed,
_1));
return seed;
}
 
M

Markus Dehmann

Possibly you can use boost::hash_combine<int> across the vector
(warning, unchecked):
std::size_t vectorhash(std::vector<int> f){
size_t seed = 0;
for_each(f.start(), f.end(), boost::bind(hash_combine<int>, seed,
_1));
return seed;

}

Perfect! Apparently it gets even easier. After reading this I googled
for hash_combine and found hash_range:

std::vector<std::string> some_strings;
std::size_t hash = boost::hash_range(some_strings.begin(),
some_strings.end());

(http://www.boost.org/doc/html/hash/combine.html)

M.
 
J

James Kanze

Perfect! Apparently it gets even easier. After reading this I googled
for hash_combine and found hash_range:
std::vector<std::string> some_strings;
std::size_t hash = boost::hash_range(some_strings.begin(),
some_strings.end());

You might want to check the implementation, to see if the
generated hash code is adequate for your use. (The examples
suggest that it has problems for certain data sets, that e.g.
std::vector<int>( 1 ) and std::vector<int>( 100 ) will hash
equal. But you'd have to look at the actual implementation to
be sure.)

(My own implementation of generic hashing uses FNV, although I'm
not convinced that this is really better than a simple Mersenne
prime hash. it also defines a HashAccumulator, so you can use
std::accumulate, and easily combine several sequences, if that's
what you need.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,196
Messages
2,571,036
Members
47,631
Latest member
kukuh

Latest Threads

Top