我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<std::string>()(class_.m_name);
}
std::size_t operator()(const std::string &name) const
{
return std::hash<std::string>()(name);
}
std::size_t operator()(const char* name) const
{
return std::hash<std::string>()(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<MyClass, MyClass::Hash, MyClass::Equal> set;
// std::unordered_set<MyClass, MyClass::Hash> 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 << L"set contains key1." << std::endl;
} else {
std::wcout << L"set doesn't contain key1." << std::endl;
}
return 0;
}
但是我在调用时不断收到编译器错误contains()
:
错误:没有匹配的函数来调用‘std::unordered_set<MyClass, MyClass::Hash, MyClass::Equal>::contains(const char [5])’[...]
我不知道为什么,也找不到任何有关它的资源。
我想我遗漏了一些东西,因为下面的代码使用起来没有问题std::string
:
int main()
{
std::unordered_set<std::string> set;
// Add sample elements to the set
set.emplace("key1");
set.emplace("key2");
// Check if the set contains "key1"
if (set.contains("key1")) // Why does this not work?
{
std::wcout << L"set contains key1." << std::endl;
} else {
std::wcout << L"set doesn't contain key1." << std::endl;
}
return 0;
}