首页 > 解决方案 > 如何在地图中查找字符

问题描述

我需要使用 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;
            }
        }
    }

};

标签: c++

解决方案


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;
               }
    );

推荐阅读