我有 map ,其中的键是 std::string。我想在 map 中找到那些以 "DUPA/"
前缀开头的元素。找到下界很容易,但上界有点问题。我写了这样一段代码:
const char* prefix = "DUPA/";
const char* firstAfterPrefix = "DUPA0";
auto prefixedBeginIt = myMap.upper_bound(prefix);
auto prefixedEndIt = myMap.lower_bound(firstAfterPrefix);
代码工作正常,但我认为它不够优雅,因为必须知道 0
在 ASCII 表中位于 /
的第一个。第二种方法是复制前缀并增加最后一个符号。你知道更优雅的解决方案吗?
最佳答案
我觉得你说的方案已经是最优雅的了。 KISS方式损失了很多性能,即每次都检查key:
while(prefixedBeginIt->first == prefix)
{
//...
++prefixedBeginIt;
}
因此我认为计算下一个字符是最好的方法:
std::string firstAfterPrefix = prefix;
++firstAfterPrefix[firstAfterPrefix.length() - 1];
auto prefixedEndIt = myMap.lower_bound(firstAfterPrefix);
关于c++ - 在 std::map 中查找具有给定前缀的键或在 std::set 中查找元素的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717939/