我有一个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库!
发布于 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");
https://stackoverflow.com/questions/9349797
复制相似问题