在映射中查找部分字符串匹配项
To find partial string match in map
>我有一个地图测试,它的初始化如下
test["auto works"] = 1;
test["before word"] = 2;
test["before list"] = 3;
test["before pattern"] = 4;
test["before me"] = 5;
test["before hen"] = 6;
test["has float"] = 7;
我有一个字符串搜索,初始化为"在我之前 grep lot"。
现在我想在测试地图中找到搜索字符串。理想情况下,我希望在测试地图中寻找更好的搜索字符串"在我之前 grep lot"。
输出应为 5。
请帮帮我。
使用test.lower_bound(search)
(文档)。
尝试以下方法
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <iterator>
int main()
{
std::map<std::string, int> test;
test["auto works"] = 1;
test["before word"] = 2;
test["before list"] = 3;
test["before pattern"] = 4;
test["before me"] = 5;
test["before hen"] = 6;
test["has float"] = 7;
std::string s( "before me grep lot" );
auto it = test.lower_bound( s );
size_t prev = 0, next = 0;
if ( it != test.begin() )
{
auto pos = std::mismatch( s.begin(), s.end(),
std::prev( it )->first.begin(), std::prev( it )->first.end() );
prev = std::distance( s.begin(), pos.first );
}
if ( it != test.end() )
{
auto pos = std::mismatch( s.begin(), s.end(),
it->first.begin(), it->first.end() );
prev = std::distance( s.begin(), pos.first );
}
std::string target = prev < next ? it->first : std::prev( it )->first;
std::cout << "The closest item is test["" << target << ""] = " << test[target] << std::endl;
}
程序输出为
The closest item is test["before me"] = 5
如果您的编译器标准库不支持算法 std::与四个参数不匹配,则 if 语句可能如下所示
if ( it != test.begin() )
{
std::cout << std::prev( it )->first << std::endl;
std::string::size_type n = std::min( s.size(), std::prev( it )->first.size() );
auto pos = std::mismatch( s.begin(), std::next( s.begin(), n ),
std::prev( it )->first.begin() );
prev = std::distance( s.begin(), pos.first );
}
if ( it != test.end() )
{
std::cout << it->first << std::endl;
std::string::size_type n = std::min( s.size(), std::prev( it )->first.size() );
auto pos = std::mismatch( s.begin(), std::next( s.begin(), n ),
it->first.begin() );
prev = std::distance( s.begin(), pos.first );
}
相关文章:
- 找到具有最多子串栅栏的字符串排列
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 没有使用两种类型的字符串进行匹配的函数调用
- 如何修复"找不到系统(字符串)的匹配项
- 错误:调用"std::basic_ifstream<char>::basic_ifstream(std::__cxx11::字符串&)"没有匹配函数
- 错误:调用"人脸检测器::人脸检测器(std::__cxx11::字符串)"没有匹配函数
- 正在检查字符串以匹配Char变量
- Q_DECLARE_INTERFACE()和Q_PLUGIN_METADATA(),接口id字符串需要匹配
- C++11 正则表达式与字符串不匹配
- 返回的字符串和提取的字符串不匹配
- 使用后缀数组和 LCP(-LR) 实现字符串模式匹配
- 生成与集合中的字符串不匹配的字符串
- _stricmp返回错误的值,而字符串确实匹配.该怎么办
- C++中两个字符串之间匹配的字符数
- 如何使用标准库(包括boost)实现简单的字符串模式匹配
- 定位字符串中匹配的单词
- C++ regex_match match_continuous标志与开始子字符串不匹配
- 字符串模式匹配和插入
- 字符串文字匹配bool重载,而不是std::String