首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >与std::map的键部分匹配

与std::map的键部分匹配
EN

Stack Overflow用户
提问于 2012-02-19 21:56:54
回答 1查看 19.2K关注 0票数 28

我有一个std::map,我想使用子字符串搜索一个键。例如,我有以下代码:

#include <iostream>
#include <map>
#include <string>
using namespace std;

typedef std::map<std::string, std::string> TStrStrMap;
typedef std::pair<std::string, std::string> TStrStrPair;

int main(int argc, char *argv[])
{
    TStrStrMap tMap;

    tMap.insert(TStrStrPair("John", "AA"));
    tMap.insert(TStrStrPair("Mary", "BBB"));
    tMap.insert(TStrStrPair("Mother", "A"));
    tMap.insert(TStrStrPair("Marlon", "C"));

    return 0;
}

现在,如果"Marla“存储在map中,我想搜索包含子字符串"Marl”而不是"Marlon“的位置。我想找一些以"Marl“开头的东西。我最多只能找到一个位置。这个是可能的吗?如果是这样的话,是怎么做的?

我不想使用任何Boost库!

EN

回答 1

Stack Overflow用户

发布于 2012-02-19 22:05:42

typedef TStrStrMap::value_type map_value_type;

struct key_contains_substring
   : std::binary_function<map_value_type, std::string, bool>
{
    bool operator()(const map_value_type& map_value, const std::string& substr)
    {
         return std::search(map_value.first.begin(), map_value.first.end(),
                    substr.begin(), substr.end()) != map_value.first.end();  
    }
};

...


TStrStrMap::const_iterator it = std::find_if(tMap.begin(), tMap.end(), 
        std::bind2nd(key_contains_substring(), "Marl");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9349797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档