struct作为map的key
时间: 2023-06-11 21:06:24 浏览: 45
可以使用`std::map`来存储`struct`类型的对象,只需要定义一个比较函数或者使用默认的比较函数即可。例如,假设我们有一个`Person`结构体,包含姓名和年龄:
```cpp
#include <iostream>
#include <string>
#include <map>
struct Person {
std::string name;
int age;
};
```
我们可以定义一个比较函数来比较两个`Person`对象的大小,例如按照姓名进行比较:
```cpp
bool operator<(const Person& lhs, const Person& rhs) {
return lhs.name < rhs.name;
}
```
然后就可以使用`std::map`来存储`Person`对象了:
```cpp
int main() {
std::map<Person, std::string> persons;
persons[{ "Alice", 25 }] = "Alice's info";
persons[{ "Bob", 30 }] = "Bob's info";
persons[{ "Charlie", 20 }] = "Charlie's info";
for (const auto& p : persons) {
std::cout << p.first.name << " (" << p.first.age << "): " << p.second << std::endl;
}
return 0;
}
```
输出结果如下:
```
Alice (25): Alice's info
Bob (30): Bob's info
Charlie (20): Charlie's info
```
注意,该方法需要保证`operator<`的实现满足严格弱序关系,即:
1. 对于任意`a`,`a < a`为`false`;
2. 对于任意`a`和`b`,如果`a < b`为`true`,那么`b < a`为`false`;
3. 对于任意`a`、`b`和`c`,如果`a < b`为`true`,`b < c`为`true`,那么`a < c`为`true`。