hash<Location>
时间: 2023-07-08 08:52:56 浏览: 51
hash<Location> 是指对于 Location 类型的对象进行哈希运算,返回一个哈希值。在 C++ 中,可以通过重载 std::hash 模板来实现对自定义类型的哈希。具体实现方式可以参考以下代码:
```cpp
#include <functional>
struct Location {
int x;
int y;
// 哈希函数
friend std::size_t hash_value(const Location& l) {
std::size_t seed = 0;
// 使用 std::hash<int> 对 x 和 y 进行哈希
seed ^= std::hash<int>()(l.x) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= std::hash<int>()(l.y) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
// 声明 std::hash<Location>
namespace std {
template<>
struct hash<Location> {
std::size_t operator()(const Location& l) const {
return hash_value(l);
}
};
}
```
这里的哈希函数使用了 std::hash<int> 对 Location 中的 x 和 y 分别进行哈希,然后将哈希值进行异或运算和移位操作得到最终的哈希值。最后,通过重载 std::hash 模板来定义 std::hash<Location> 类型,使得可以在 STL 容器中使用 Location 类型作为键值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
<script> import Home from './Home.vue' import About from './About.vue' import NotFound from './NotFound.vue' const routes = { '/': Home, '/about': About } export default { data() { return { currentPath: window.location.hash } }, computed: { currentView() { return routes[this.currentPath.slice(1) || '/'] || NotFound } }, mounted() { window.addEventListener('hashchange', () => { this.currentPath = window.location.hash }) } } </script> <template> Home | About | Broken Link <component :is="currentView" /> </template>解释每一句的作用
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)