std::map 如何使用GUID
时间: 2023-12-15 17:32:19 浏览: 163
random-guid:生成随机 GUID
以下是使用std::map存储和使用GUID的示例代码:
```cpp
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
// GUID结构体
struct GUID {
int data1;
short data2;
short data3;
char data4[8];
};
// 重载小于运算符,用于在std::map中排序
bool operator<(const GUID& lhs, const GUID& rhs) {
if (lhs.data1 != rhs.data1) {
return lhs.data1 < rhs.data1;
}
if (lhs.data2 != rhs.data2) {
return lhs.data2 < rhs.data2;
}
if (lhs.data3 != rhs.data3) {
return lhs.data3 < rhs.data3;
}
return std::lexicographical_compare(lhs.data4, lhs.data4 + 8, rhs.data4, rhs.data4 + 8);
}
// 将GUID转换为字符串
std::string GuidToString(const GUID& guid) {
char buf[40];
sprintf_s(buf, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
guid.data1, guid.data2, guid.data3,
guid.data4[0], guid.data4[1], guid.data4[2], guid.data4[3],
guid.data4[4], guid.data4[5], guid.data4[6], guid.data4[7]);
return buf;
}
// 在std::map中查找GUID
std::map<GUID, std::string>::iterator FindGuid(std::map<GUID, std::string>& guidMap, const GUID& guid) {
return std::find_if(guidMap.begin(), guidMap.end(), [&](const std::pair<GUID, std::string>& pair) {
return memcmp(&pair.first, &guid, sizeof(GUID)) == 0;
});
}
int main() {
// 创建一个std::map,用于存储GUID和对应的字符串
std::map<GUID, std::string> guidMap;
// 添加一些GUID和字符串
GUID guid1 = { 0x12345678, 0x9ABC, 0xDEF0, {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0} };
guidMap[guid1] = "GUID 1";
GUID guid2 = { 0x87654321, 0xCDEF, 0x0FED, {0x21, 0x43, 0x65, 0x87, 0x09, 0x8B, 0xAD, 0xCF} };
guidMap[guid2] = "GUID 2";
// 在std::map中查找GUID
GUID guid3 = { 0x12345678, 0x9ABC, 0xDEF0, {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0} };
auto iter = FindGuid(guidMap, guid3);
if (iter != guidMap.end()) {
std::cout << "Found GUID: " << GuidToString(iter->first) << ", value: " << iter->second << std::endl;
} else {
std::cout << "GUID not found" << std::endl;
}
return 0;
}
```
阅读全文