Функция члена как компаратор карты?

Я знаю, как создать функцию, которая служит в качестве пользовательского компаратора карты:

std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(MapComparator);

bool MapComparator(std::string left, std::string right)
{
return left < right;
}

Но я не знаю, как сделать то же самое с член функция:

bool MyClass::MapComparator(std::string left, std::string right)
{
return left < right;
}

2

Решение

У вас есть несколько вариантов:

В C ++ 11 вы можете использовать лямбду:

std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(
[](string lhs, int rhs){ // You may need to put [this] instead of [] to capture the enclosing "this" pointer.
return MapComparator(lhs, rhs); // Or do the comparison inline
});

Если функция статическая, используйте :: синтаксис:

class MyClass {
public:
static bool MyClass::MapComparator(std::string left, std::string right);
};
...
std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(MyClass::MapComparator);

Если функция нестатическая, создайте статическую оболочку, член или не член и вызовите функцию-член из нее.

2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector