jeudi 30 mars 2023

is it bad to hash raw buffer by using std::string as a wrapper?

C++ std::hash<> has some standard specializations for fix-sized basic types, and std::string family, which is the only one having variable memory size(and std::vector<bool> too, unconcerned here)

once we tend to hashing multiple variables or a buffer, we need to implement a hashing algorithom, which is hard to remember and easily be wrong.

std::string can be used as a buffer(std::vector<std::byte> is better, I know), and if we store utf-8 string(which have bytes other than ASCII) in it, it is likely hashes well too.

what is the disadvantage like this:

std::string hash_wrapper(4 * 4, '\0');
int* write_ptr = reinterpret_cast<int*>(hash_wrapper.data());

write_ptr[0] = val1;
write_ptr[1] = val2;
write_ptr[2] = val3;
write_ptr[3] = val4;

std::unordered_map<std::string, int> ht;
ht[hash_wrapper] = val;

Aucun commentaire:

Enregistrer un commentaire