加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在std :: map中部分匹配长键

发布时间:2020-12-16 09:47:46 所属栏目:百科 来源:网络整理
导读:我在我的项目中使用了std :: map,因为我想要将几个不同的字符串相互映射.例如,我可能会创建一个类似于此的地图: std::mapstd::string,std::string map;map["test"] = "Foo";map["blah"] = "Drei";map["fayh"] = "Najh";// And so on... 我想使用比地图中的
我在我的项目中使用了std :: map,因为我想要将几个不同的字符串相互映射.例如,我可能会创建一个类似于此的地图:

std::map<std::string,std::string> map;

map["test"] = "Foo";
map["blah"] = "Drei";
map["fayh"] = "Najh";
// And so on...

我想使用比地图中的键长的键来找到这些值,即部分匹配键.地图中的所有键与它们所比较的键共享相同的前缀

这就是我想要实现的目标:

// Same map as earlier
std::cout << map.find('test123').second;    // Should output 'Foo'
std::cout << map.find('test_2165').second;  // Should output 'Foo' as well
std::cout << map.find('tes').second;        // Key not found
std::cout << map.find('fayh_TK_Ka').second; // 'Najh'

我希望你明白我的意思.我想有效地检索映射到键的值,这些键对应于比它们大的比较键,但共享相同的前缀(例如’test’).

我不知道std :: map是否是这种情况下的最佳选择,如果没有,请告诉其他选项.

注意:我尝试使用带有std :: greater_equalas键比较器和lower_bound方法的映射,但我最终遇到了运行时错误,我也质疑这种方法的效率.

解决方法

以下将满足您的需求:

std::string my_find( const std::string& s )
{
    auto it = map.lower_bound( s );
    if( it != map.begin() ) {
        if( it != map.end() && it->first == s ) return it->second; // exact match
        --it;
        if( it->first == s.substr( 0,it->first.size() ) ) {
            return it->second;
        }
    }
    return "Key not found";
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读