介绍一下map类并给出几个例子并讲解
时间: 2023-07-04 10:14:22 浏览: 49
map类是C++ STL中的一个关联容器,它提供了一种键-值对的映射关系,即每个键都对应一个唯一的值。map中的键和值可以是任意类型,但键必须是可比较的,它们按照一定的顺序进行排序。map内部使用红黑树实现,因此查找、插入和删除操作的时间复杂度均为O(logN)。
下面是几个使用map的例子:
1. 统计单词出现的次数
```c++
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
string sentence = "Hello world, this is a sentence. How many words are there?";
map<string, int> wordCount;
string word = "";
for (int i = 0; i < sentence.length(); i++) {
if (sentence[i] == ' ' || sentence[i] == ',' || sentence[i] == '.') {
if (word.length() > 0) {
wordCount[word]++;
word = "";
}
} else {
word += sentence[i];
}
}
if (word.length() > 0) {
wordCount[word]++;
}
for (auto it = wordCount.begin(); it != wordCount.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
上述代码使用map统计一个字符串中每个单词出现的次数。
2. 存储学生信息
```c++
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct Student {
string name;
int age;
string gender;
};
int main()
{
map<int, Student> studentMap;
Student s1 = {"Tom", 18, "male"};
Student s2 = {"Alice", 19, "female"};
Student s3 = {"John", 20, "male"};
studentMap[1] = s1;
studentMap[2] = s2;
studentMap[3] = s3;
for (auto it = studentMap.begin(); it != studentMap.end(); it++) {
cout << "ID: " << it->first << endl;
cout << "Name: " << it->second.name << endl;
cout << "Age: " << it->second.age << endl;
cout << "Gender: " << it->second.gender << endl;
cout << endl;
}
return 0;
}
```
上述代码使用map存储学生信息,其中键为学生的ID,值为一个结构体,包含学生的姓名、年龄和性别。
3. 实现字典
```c++
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, string> dictionary;
dictionary["apple"] = "苹果";
dictionary["banana"] = "香蕉";
dictionary["orange"] = "橙子";
dictionary["peach"] = "桃子";
string word;
while (true) {
cout << "请输入一个单词(输入exit退出):";
cin >> word;
if (word == "exit") {
break;
}
if (dictionary.find(word) != dictionary.end()) {
cout << word << "的意思是:" << dictionary[word] << endl;
} else {
cout << "抱歉,查不到这个单词。" << endl;
}
}
return 0;
}
```
上述代码实现了一个简单的字典,用户输入一个单词,程序通过map查找并显示该单词的含义。