The keys in a map
are lexicographically sorted, so that if one key A
is going to be a prefix of another key B
then:
A
comes before B
A
is also a prefix of any key between A
and B
Therefore, we can perform a simple scan in the map (m
here):
auto current = m.begin();
for (auto it = next(current), end = m.end(); it != end; ++it ) {
// Note: if current is not a prefix of "it", then it cannot be a prefix
// of any key that comes after "it", however of course "it" could
// be such a prefix.
// current is not a prefix of "it" if "it" is shorter
if (it->first.size() <= current->first.size()) { current = it; continue; }
// current is not a prefix of "it"
if (it->first.substr(0, current->first.size()) != current->first) {
current = it; continue;
}
// current is a prefix
std::cout << "'" << current->first << "' is a prefix of '" << it->first << "'\n";
}
Note: computing a substring is not necessary, a starts_with
function which does not allocate would be much better, however it does get the point across.
You can check the full code here.