Home > database >  C Map with customized comparator does not work correctly
C Map with customized comparator does not work correctly

Time:06-09

Map with a customized comparator does not work as expected.

Code:

struct Comp {
    const bool operator()(const int x, const int y) const {
        return abs(x) < abs(y);
    }
};

map<int, int, Comp> func(vector<int>& arr) {
    map<int, int, Comp> mp;
    for (int x : arr) {
        mp[x]  ;
    }
    return mp;
};

int main() {
    vector<int> arr = { 4, -2, 2, -4 };
    map<int, int, Comp> res = func(arr);

    for (auto it : res) {
        cout << it.first << " -> " << it.second << endl;
    }

    return 0;
}

Output:

-2 -> 2
4 -> 2

Expected:

-4 -> 1
-2 -> 1
2 -> 1
4 -> 1

Does anyone know if C is wrong or my expected result is wrong?

CodePudding user response:

map uses the comparator to test ordering, but also to know if two keys are equal, i.e., if comp(a,b) == false and comp(b,a) == false, then it means that the 2 keys are equal and that they should be considered the same, even though the bits in memory are different.

In your case, comp(-2,2) and comp(2,-2) are both false so it considers it as a single entry. Same thing for -4 and 4. Since the two first inserted keys are 4 and -2, these are the two keys that are set in the map. And since both negative and positive keys point to the same entry, then it increments each value twice.

  • Related