c++ - 在 std::map 中查找具有给定前缀的键或在 std::set 中查找元素的优雅方法

标签 c++ prefix stdmap stdset

我有 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/

相关文章:

database - 在 phpmyadmin 中重命名表名的前缀?

c++ - 使用 std::map::extract 修改键

c++ - 以自定义类作为键的 std::map 始终返回 1 的大小

包含列表的 c++ 映射

c++ - 非数组类型的指针算法

c++ - 字符串中的十六进制到整数中的十六进制

c++ - 将字符串传递给 file.open();

c++ - 为什么变量 “sum”必须在函数中而不是在main之外初始化?

Emacs:如何绑定(bind)到 M-s?

jquery-ui - jqueryui 自动完成 : lists entries with search terms in middle