如何遍历Map的每个元素是否含有关键词
时间: 2024-05-14 16:17:39 浏览: 17
遍历 Map 中的每个元素可以使用迭代器,然后对每个元素进行关键词匹配。以下是一个示例代码:
```c++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> myMap = {
{"apple", 3},
{"banana", 2},
{"orange", 1},
{"grape", 5}
};
std::string keyword = "an";
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
if (it->first.find(keyword) != std::string::npos) {
std::cout << it->first << " " << it->second << std::endl;
}
}
return 0;
}
```
在这个示例代码中,我们定义了一个 `std::map<std::string, int>` 类型的变量 `myMap` 并初始化它。然后,我们定义了一个字符串 `keyword` 作为关键词。之后,我们使用迭代器遍历了 `myMap` 中的每个元素,并使用 `find` 函数查找该元素的键(即字符串)中是否包含 `keyword`,如果包含,则输出该元素的键和值。
需要注意的是,`find` 函数返回匹配到的第一个字符的位置,如果没有匹配到,则返回 `std::string::npos`。