Search code examples
c++boostunordered-mapboost-unordered

Dynamic equal_to function unordered_map boost


I have an unordered map string to int which uses a custom equal_to function defined as:

bool hashEqual::operator ()(const string &a, const string &b) const
{
    if (a.size() != b.size())
        return false;

    return std::inner_product(
        a.begin(), a.end(), b.begin(),
        0, std::plus<unsigned int>(),
        std::not2(std::equal_to<std::string::value_type>())
        ) <= 8;  
}           

Basically what it does is if two keys have a hamming distance equal or less than 8, then is the same key.

The thing is I want the distance threshold to be dynamic in order to let the user set it through the command line. Instead of 8, a variable threshold or something like this.

I'm not looking for a hack like a global variable (unless it's the only way to achieve this) but for the "good way".


Solution

  • I figured it out.

    All is done in the class hashEqual. I changed the definition like this:

    class hashEqual {
        private:
            int th;
        public:
           hashEqual();
            hashEqual(int th) { this->th = th; }; // This implemetation on the .cpp
            bool operator ()(const string &a, const string &b) const;
    };
    

    the operator() implementation:

    bool hashEqual::operator ()(const string &a, const string &b) const
    {
        if (a.size() != b.size())
            return false;
    
        return std::inner_product(
            a.begin(), a.end(), b.begin(),
            0, std::plus<unsigned int>(),
            std::not2(std::equal_to<std::string::value_type>())
            ) <= this->th;  
    }   
    

    And in the constructor of the unordered_map:

    boost::unordered_map<string, unsigned int, boost::hash<string>, hashEqual> myMap(size, boost::hash<string>(), hashEqual(threshold));