如何在c++映射中提取具有相同前缀的记录

how to extract the records with same prefix in C++ map?

本文关键字:前缀 记录 提取 c++ 映射      更新时间:2023-10-16

现在,我只知道在一个地图中有几个具有相同前缀"head_"的记录。如果我不知道它们在这个映射中的确切键,我如何提取所有这些记录?任何想法?

您必须遍历映射。但是,您可以通过调用std::map::lower_bound,并使用key等于您想要的前缀来有效地找到起点。

void extract_keys(const std::map<std::string, int>& some_map){
    auto iter = some_map.lower_bound("head_");
    while (iter->first.find("head_") == 0){
        //do things with key, value pair
        ++iter;
    }
}

上面的代码应该可以工作,但是我承认我没有测试它。(任何错误都是可以修复的)