Search code examples
c++dictionarygmp

Using mpz_t as key for std::map


I am trying to build a map from mpz_t keys to uint values. I don't know why but the mpz_t keys can somehow not be looked up in the map.

mpz_t leftSideValues[1 << 20];

int main()
{
    std::map<mpz_t, uint> leftSide;

    for (uint i = 0; i < 1 << 20; i++)
    {
        mpz_init(leftSideValues[i]);

        // compute some stuff here...

        // now save the computed value to our map
        leftSide[leftSideValues[i]] = i;

        // do a lookup to see whether our value can be found
        std::cout << leftSide.at(leftSideValues[i]) << " -- " << i << std::endl;
    }

    return 0;
}

The expected output would be a lot of lines looking like "0 -- 0", "1 -- 1" etc. but that does not happen. Instead:

terminate called after throwing an instance of 'std::out_of_range'
  what():  map::at

Is there some other step that I need to take to make mpz_t be usable in a map?


Solution

  • It seems map cannot compare two mpz_t instances.

    According to the C++ reference maps are implemented as binary search trees. Therefore if elements cannot be compared search is impossible.

    Adding a comparer fixed this problem:

    struct mpzCompare
    {
        bool operator() (const mpz_t val1, const mpz_t val2) const
        {
            return mpz_cmp(val1, val2) > 0;
        }
    };
    
    std::map<mpz_t, uint, mpzCompare> leftSide;