告诉我 结构体作为key, map的用法,写出完整代码
时间: 2024-01-02 12:03:25 浏览: 39
好的,以下是关于结构体作为key的map用法的完整示例代码:
```cpp
#include <iostream>
#include <map>
#include <string>
using namespace std;
// 定义一个结构体作为map的key
struct Student {
string name;
int age;
// 重载小于号运算符
bool operator<(const Student& s) const {
if (name != s.name) {
return name < s.name;
}
return age < s.age;
}
};
int main() {
// 定义一个map,以Student结构体作为key,int类型作为value
map<Student, int> studentMap;
// 向map中插入元素
studentMap[{ "Alice", 18 }] = 1;
studentMap[{ "Bob", 20 }] = 2;
studentMap[{ "Charlie", 19 }] = 3;
// 遍历map
for (auto& it : studentMap) {
cout << "Name: " << it.first.name << ", Age: " << it.first.age << ", Value: " << it.second << endl;
}
return 0;
}
```
在上述示例代码中,我们定义了一个名为`Student`的结构体,包含`name`和`age`两个成员变量,并且重载了小于号运算符,以便在`map`中进行比较。接着,我们定义了一个`map`,以`Student`结构体作为key,`int`类型作为value。然后,我们向`map`中插入了三个元素,并且遍历了`map`,输出了每个元素的`name`、`age`和`value`。