找到std :: map中给定前缀或std :: set中元素的键的优雅方法

jas*_*mar 9 c++ stdmap prefix stdset

我有地图,哪些键是std :: string.我想在地图中找到以"DUPA/"prefix 开头的那些元素.找到下限很容易,但上限有点问题.我写了这样一段代码:

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

代码工作正常,但我不认为它是优雅的,因为必须知道它0/在ASCII表中的第一个.第二种方法是复制前缀和增加最后一个符号.你知道更优雅的解决方案吗?

Som*_*ken 6

我认为你提到的解决方案已经是最优雅的了.KISS方式失去了很多性能,即每次检查密钥:

while(prefixedBeginIt->first == prefix)
{
 //...
 ++prefixedBeginIt;
}
Run Code Online (Sandbox Code Playgroud)

因此,我认为计算下一个字符是最好的方法:

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

  • 是的,我认为它可能是最好的解决方案,但我会在这个特定问题中使用char []而不是std :: string.但作为通用解决方案,只要最后一个字符不等于MAX_CHAR,它就是最好的;) (2认同)