Search code examples
c++prefixstdmapstdset

Elegant way to find keys with given prefix in std::map or elements in std::set


I have map, which keys are std::string. I want to find those elements in the map which starts with "DUPA/" prefix. Finding lower bound is easy but upper bound is a bit problematic. I wrote such piece of code:

const char* prefix = "DUPA/";
const char* firstAfterPrefix = "DUPA0";
auto prefixedBeginIt = myMap.upper_bound(prefix);
auto prefixedEndIt = myMap.lower_bound(firstAfterPrefix);

The code works fine but I don't consider it to be elegant, as one has to know that 0 is first next to / in ASCII table. Second way would be to copy prefix and increment last sign. Do you know more elegant solution?


Solution

  • I think the solution you mentioned is already the most elegant. The KISS way loses a lot of performance, that is, checking the key each time:

    while(prefixedBeginIt->first == prefix)
    {
     //...
     ++prefixedBeginIt;
    }
    

    Thus I think calculating the next char is the best approach:

    std::string firstAfterPrefix = prefix;
    ++firstAfterPrefix[firstAfterPrefix.length() - 1];
    auto prefixedEndIt = myMap.lower_bound(firstAfterPrefix);