How can I solve this compilation error?


  • 1
    Y

    I've been getting compilation error:

    required from 'class std::unordered_map<std::pair<float, float>, int>'
    

    I'm wondering it's my issue or problem of leetcode. Here's my code:

    #include<unordered_map>
    #include<utility>
    
    using namespace std;
    
    class Solution {
    public:
        int maxPoints(vector<Point> &points) {
            unordered_map<pair<float,float>, int> nonverticals;
            unordered_map<int, int> verticals;
            for(int i = 0; i < points.size(); i++) {
                for(int j = i + 1; j < points.size(); j++) {
                    if(points[j].x == points[i].x) {
                        verticals[points[i].x] = (verticals.count(points[i].x) == 0) ? 1 : verticals[points[i].x] + 1;
                    } else {
                        pair<float,float> l = getLine(points[i], points[j]);
                        nonverticals[l] = (nonverticals.count(l) == 0) ? 1 : nonverticals[l] + 1;
                    }
                }
            }
            
            int max = 0;
            for(auto& nonvertical : nonverticals) {
                if(nonvertical.second > max) max = nonvertical.second;
            }
            for(auto& vertical : verticals) {
                if(vertical.second > max) max = vertical.second;
            }
            
            return max;
        }
        
        pair<float,float> getLine(Point &p1, Point &p2) {
            pair<float,float> l;
            l.first = (float)(p1.y - p2.y) / (float)(p1.x - p2.x);
            l.second = (float)(p1.y) - l.first * p1.x;
            return l;
        }
    };

  • 0

    According to this thread -- Using C++ unordered_map with pair of values for key,

    You need to supply a hash function object and a predicate for comparing equality of a pair<int, int>. Such things do not exist unless you create them, and the compiler cannot instantiate the unordered_map template without them. Hence the bitter complaints you are seeing.


  • 0
    Y

    Aha, thanks for answering. I used struct and was told I need a hash function so I changed to pair believing that it should have be implemented...


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.