I have an std::map and I want to search for a key using a substring. For exampe
#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;
}
I want to search for the position that holds the substring "Marl" and not "Marlon". Is it possible? How?
EDIT: no boost libraries!
When your substring is a prefix as in your example, you can use
lower_bound
to search for"Marl"
.This does not work for non-prefix substrings: in the general case, searching a map is not much different from searching other containers.
You can't efficiently search for substring, but you can for prefix:
This prints:
To search for a substring of a key in a map you have no choice but to either use a new map on a special kind of key type or to search your map in O(n).
std::map
uses (by default)operator<()
for ordering keys and for searching, and that compare function forstd::string
is a plain lexicographical compare.If you create a new map on a special key type that has
operator<()
compare on basis of a substring take note that this will also affect the decision of whether a new element to insert would be a duplicate. In other words, such a map will only have elements that are not substrings of each other.The O(n) search practically means you use
std::find()
over the map, with a custom predicate that takes astd::pair<std::string,std::string>
and returns true if the second element of the pair is a substring of the first.