unordered_map能否使用GUID当做key
时间: 2023-12-10 10:36:04 浏览: 28
可以使用GUID作为unordered_map的key。GUID是一个128位的全局唯一标识符,可以用作unordered_map的key,只要实现了GUID的哈希函数和比较函数即可。以下是一个使用GUID作为key的unordered_map的示例代码:
```c++
#include <iostream>
#include <unordered_map>
#include <string>
#include <sstream>
#include <iomanip>
#include <windows.h>
using namespace std;
// 定义GUID的哈希函数
struct GUIDHash {
size_t operator()(const GUID& guid) const {
return guid.Data1 ^ guid.Data2 ^ guid.Data3 ^ *(reinterpret_cast<const int*>(&guid.Data4[0])) ^ *(reinterpret_cast<const int*>(&guid.Data4[4]));
}
};
// 定义GUID的比较函数
struct GUIDEqual {
bool operator()(const GUID& guid1, const GUID& guid2) const {
return memcmp(&guid1, &guid2, sizeof(GUID)) == 0;
}
};
int main() {
unordered_map<GUID, string, GUIDHash, GUIDEqual> myMap;
// 生成一个GUID
GUID guid;
CoCreateGuid(&guid);
// 将GUID作为key插入unordered_map
myMap[guid] = "Hello World!";
// 从unordered_map中查找GUID对应的value
string value = myMap[guid];
cout << value << endl;
return 0;
}
```