我知道struct X通过定义一个单独的散列函数struct 可以为a 定义一个散列函数:
struct hash_X {
size_t operator()(const X &x) const {}
bool operator()(const X &a, const X &b) const {}
};
int main() {
unordered_set<X, hash_X, hash_X> s;
}
Run Code Online (Sandbox Code Playgroud)
但我正在寻找operator<可以附加到struct X自身的东西,例如set:
struct X {
bool operator<(const X &other) const {}
};
int main() {
set<X> s;
}
Run Code Online (Sandbox Code Playgroud)
最终目标是这样的:
struct X {
size_t operator()(void) const {}
bool operator()(const X &other) const {}
};
int main() {
unordered_set<X> s;
}
Run Code Online (Sandbox Code Playgroud)
这在C++中是否可行?
std::unordered_set在std命名空间内定义.它使用std::hash结构来散列许多不同类型.如果您希望能够使用std::unordered_set<X>(不向声明添加太多信息),则必须创建std::hash模板的另一个重载,以便使其对您的结构进行哈希处理.
您应该能够通过执行以下操作来使其正常工作:
# include <unordered_set>
struct X {
size_t operator()(void) const {}
bool operator()(const X &other) const {}
};
namespace std {
template<>
struct hash<X> {
inline size_t operator()(const X& x) const {
// size_t value = your hash computations over x
return value;
}
};
}
int main() {
std::unordered_set<X> s;
}
Run Code Online (Sandbox Code Playgroud)
Andalso,您必须为您的结构提供重载std::equal_to或比较运算符(operator==()).您应该添加以下内容之一:
struct X {
...
inline bool operator==(const X& other) const {
// bool comparison = result of comparing 'this' to 'other'
return comparison;
}
};
Run Code Online (Sandbox Code Playgroud)
要么:
template <>
struct equal_to<X> {
inline bool operator()(const X& a, const X& b) const {
// bool comparison = result of comparing 'a' to 'b'
return comparison;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3978 次 |
| 最近记录: |