Función Hash de C++ para cadena en mapa desordenado


Parece que C++ no tiene una función hash para cadenas en la biblioteca estándar. ¿Es esto cierto?

¿Qué es un ejemplo práctico de usar una cadena como clave en un unordered_map que funcionará con cualquier compilador de c++?

Author: Patrick B., 2013-03-24

5 answers

C++ STL proporciona la plantilla especializaciones de std::hash para las diversas clases de cadenas. Solo puede especificar std::string como tipo de clave para std::unordered_map:

#include <string>
#include <unordered_map>

int main()
{
    std::unordered_map<std::string, int> map;
    map["string"] = 10;
    return 0;
}
 27
Author: soon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-02 10:33:48

Me encontré con esto hoy (en realidad con wstring, no string, pero es el mismo trato): usar wstring como clave en un unordered_map genera un error acerca de que no hay una función hash disponible para ese tipo.

La solución para mí fue añadir:

#include <string>

Lo creas o no, sin el include todavía tenía el tipo wstring disponible pero aparentemente NO las funciones auxiliares como el hash. Simplemente agregando la inclusión anterior lo arregló.

 16
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-13 12:47:18

En realidad, hay std::hash<std::string>

Pero ahí está cómo puedes usar otra función hash:

struct StringHasher {
    size_t operator()(const std::string& t) const {
          //calculate hash here.
    }
}

unordered_map<std::string, ValueType, StringHasher>
 13
Author: RiaD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 05:34:24

Si tiene un CustomType y desea conectarse a la infraestructura STL, esto es lo que podría hacer.

namespace std
{
//namespace tr1
//{
    // Specializations for unordered containers

    template <>
    struct hash<CustomType> : public unary_function<CustomType, size_t>
    {
        size_t operator()(const CustomType& value) const
        {
            return 0;
        }
    };

//} // namespace tr1

template <>
struct equal_to<CustomType> : public unary_function<CustomType, bool>
{
    bool operator()(const CustomType& x, const CustomType& y) const
    {
        return false;
    }
};

} // namespace std

Si luego desea crear un std::unordered_map<CustomType>, el STL encontrará las funciones hash y equal_to sin tener que hacer nada más con la plantilla. Así es como me gusta escribir mi comparador de igualdad personalizado que admite estructuras de datos desordenadas.

 7
Author: John Leidegren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-24 07:03:33

En mi caso fue realmente distracción.

Tenía un tipo X para el que implementé hashing para const & X y lo utilicé en algún lugar con

std::unordered_map<const X, int> m_map;

Entonces quería tener otro mapa que clave son del tipo X y lo hice:

std::unordered_map<X, int> map_x;

Observe la FALTA de const en el segundo caso.

 0
Author: sergiol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-02 12:03:25