帶有自定義比較器的映射無法按預期作業。
代碼:
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;
}
輸出:
-2 -> 2
4 -> 2
預期的:
-4 -> 1
-2 -> 1
2 -> 1
4 -> 1
有誰知道 C 錯了還是我的預期結果錯了?
uj5u.com熱心網友回復:
map使用比較器來測驗排序,同時也知道兩個鍵是否相等,即如果comp(a,b) == false和comp(b,a) == false,那么這意味著這兩個鍵是相等的,即使記憶體中的位不同,它們也應該被認為是相同的。
在您的情況下,comp(-2,2)并且comp(2,-2)都是錯誤的,因此它將其視為單個條目。-4 和 4 也是如此。由于第一個插入的兩個鍵是 4 和 -2,因此這是在映射中設定的兩個鍵。由于負鍵和正鍵都指向同一個條目,因此它會將每個值遞增兩次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487964.html
