Ваш код KeyLess
приводит к некорректному сравнению:
KeyLess cmp;
std::cout << cmp(Key{2, 169},Key{1, 391})<< std::endl; // yields true
std::cout << cmp(Key{1, 391},Key{2, 169})<< std::endl; // yields true
Когда оба сравнения дают ложь, это означает, что ключи равны, и когда они дают истину, поведение итератора карты не определено. Это связано с тем, что map сортирует свои элементы.
Обратите внимание, что operator()
должно быть const
, иначе программа может не скомпилироваться со стандартом C ++ 17 и более поздними версиями. Как возможный вариант:
#include <map>
#include <iostream>
using Key = std::pair<unsigned long, unsigned long long>;
struct KeyLess {
bool operator()(const Key& lhs, const Key& rhs) const {
if (lhs.first < rhs.first) {
return true;
}
else if (lhs.first > rhs.first)
return false;
if (lhs.second < rhs.second) {
return true;
}
return false;
}
};
int main()
{
std::map< Key , int, KeyLess > m;
m[Key{2, 169}] = 1;
m[Key{1, 255}] = 2;
m[Key{1, 391}] = 3;
m[Key{1, 475}] = 4;
std::cout << "Elements in map: " << m.size() << std::endl;
for(const auto &[key, value]: m) {
std::cout << "Key: " << key.first << ", " << key.second << " Value: "<< value << std::endl;
}
}