Как использовать unordered_set::contains() с собственным классом?C++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Как использовать unordered_set::contains() с собственным классом?

Сообщение Anonymous »

Я впервые использую std::unordered_set с пользовательским типом и не могу понять, чего мне не хватает, чтобы заставить метод contains() скомпилировать мой набор.
По сути, у меня есть класс, который выглядит примерно так:
class MyClass
{
// Ctor/Dtor
public:
MyClass(const std::string& name /* + other params in my real use case */) : m_name(name) {}
~MyClass() = default;

// Members
private:
std::string m_name;

// Operators
public:
// Equal operators
bool operator==(const MyClass &other) const
{
return m_name == other.m_name;
}

bool operator==(const std::string& other) const
{
return m_name == other;
}

bool operator==(const char* other) const
{
return m_name == other;
}

// Functors
public:
// Hash functor
struct Hash
{
std::size_t operator()(const MyClass &class_) const
{
return std::hash()(class_.m_name);
}

std::size_t operator()(const std::string &name) const
{
return std::hash()(name);
}

std::size_t operator()(const char* name) const
{
return std::hash()(name);
}
};

// Equal functor
struct Equal
{
bool operator()(const MyClass &lhs, const MyClass &rhs) const
{
return lhs.m_name == rhs.m_name;
}

bool operator()(const MyClass &lhs, const std::string &rhs) const
{
return lhs.m_name == rhs;
}

bool operator()(const std::string &lhs, const MyClass &rhs) const
{
return lhs == rhs.m_name;
}

bool operator()(const MyClass &lhs, const char* rhs) const
{
return lhs.m_name == rhs;
}

bool operator()(const char* lhs, const MyClass &rhs) const
{
return lhs == rhs.m_name;
}
};

};

Используя этот класс, я хочу создать std::unordered_set и проверить, существует ли элемент с именем key1. Для этого я хотел бы использовать следующий код:
int main()
{
// I tried both, but none of them seem to work
std::unordered_set set;
// std::unordered_set set;

// Add sample elements to the set
set.emplace("key1");
set.emplace("key2");

// Check if the set contains "key1"
if (set.contains("key1")) // Compile error on this line. Why does this not work?
{
std::wcout

Подробнее здесь: https://stackoverflow.com/questions/790 ... stom-class
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»