Я впервые использую 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
Как использовать unordered_set::contains() с собственным классом? ⇐ C++
Программы на C++. Форум разработчиков
-
Anonymous
1727825460
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
Подробнее здесь: [url]https://stackoverflow.com/questions/79044975/how-to-use-unordered-setcontains-with-a-custom-class[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия