c++ - 如何在地图中查找字符
问题描述
我需要使用 map 创建字典。我需要创建一个函数来显示以特定字符开头的每个单词。我创建了该函数(start_with())并且它可以工作,但我想问我是否可以使用 find() 并仅查找和显示以该字符开头的单词。
class Dictionary {
std::map<std::string, std::string>p;
public:
Dictionary(std::string filename) {
std::ifstream ifstream(filename, std::ios::app);
std::string map1, map2;
while (ifstream) {
ifstream >> map1>> map2;
p.insert(std::pair<std::string, std::string>(map1,map2));
}
}
void start_with(char c) {
std::string temp;
for (auto it = p.begin(); it != p.end(); it++) {
temp = it->first;
if (temp[0] == c) {
std::cout << it->first << " " << it->second << std::endl;
}
}
}
};
解决方案
std::for_each
从<algorithm>
是解决方案:
std::map<std::string, std::string> map {{"a","a"}, {"b", "b"}, {"c", "b"}};
char ch = 'b';
std::for_each (map.begin(), map.end(),
[ch](auto e) {
if (e.first[0] == ch)
std::cout << e.first << " "
<< e.second << std::endl;
}
);
推荐阅读
- elixir - Elixir Simple 模块仅产生“参数错误”
- java - 如何分配一个长的十六进制值,我应该在 Java 中将它分配给什么数据类型?
- javascript - Quill.js 不断从锚标签中剥离类
- python - 如何重命名通过 Django Rest Framework 上传的图像
- python - 如何卸载并重新安装 anaconda naviator
- python - 如何在更改文件名时*不*更改文件扩展名?
- julia - 朱莉娅推!需要整个数组的副本
- python - 如何在一个类中定义一个方法来创建同一个类的对象?
- python-3.6 - python3除法和精度
- python - 使用 `.rstrip()` 和 `.strip() 删除换行符 `\n`