size_t and hashing

closed account (Sw07fSEw)
I got carried away and have been reading the pages on std::unordered_map, unordered_map::hash_function and std::hash.

I learned from reading the std::hash documentation, that the function returns a hash value of type size_t. From my understanding, size_t is the size of any object in bytes. However, when I modify the example code from the std::hash page to output the return value, the output doesn't match my logic. Since the return value is of type, size_t, which is the object's size in bytes, how is the return value 10+ digits long? It makes sense that the hash value's should differ from one another and thus they'll be extremely large numbers to avoid such collisions, but why is that value of type size_t? Intuitively, I would think the return value should be of type std::long since the hash is just a long sequence of numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// hash example from http://www.cplusplus.com/reference/functional/hash/
#include <iostream>
#include <functional>
#include <string>

int main ()
{
  char nts1[] = "Test";
  char nts2[] = "Test";
  std::string str1 (nts1);
  std::string str2 (nts2);

  std::hash<char*> ptr_hash;
  std::hash<std::string> str_hash; 

  std::cout << "hashes:\n" << std::boolalpha;
  std::cout << "nts1 and nts2: " << ptr_hash(nts1) <<'\t' << ptr_hash(nts2) << '\n';
  std::cout << "str1 and str2: " << str_hash(str1) <<'\t' << str_hash(str2) << '\n';

  return 0;
}

Last edited on
size_t is a type. Like: unsigned or int. It is guaranteed to be large enough to represent the number of objects held in a container, but using a variable of type size_t does not mean the variable must represent a size.

http://en.cppreference.com/w/cpp/types/size_t

There is no such thing as std::long.

On my system:

1
2
3
4
5
6
7
8
#include <limits>
#include <iostream>

int main()
{
    std::cout << std::numeric_limits<std::size_t>::max() << '\n';
    std::cout << std::numeric_limits<unsigned long>::max() << '\n';
}
18446744073709551615
4294967295
Last edited on
Topic archived. No new replies allowed.