c++ - 使用上限和下限在 C++ 映射中找到正确的条目

标签 c++ dictionary

我正在尝试使用 upper_bound 函数优化我在 C++ map 中的搜索: map 是变量 table:

Foo& search(uint64 id, uint64 hash) {

   std::map<std::pair<uint64, uint64>, Foo>::const_iterator iter;

   std::pair<uint64, uint64> key(id, hash);
   iter = table.upper_bound(key);
   // for completeness I search for those elements which may be a match
   // they may fall into a different hash range

   for( ; iter != table.end() || iter != table.begin(); --iter ) {
         const Foo foo = iter->second;
         if(foo.id() == foo.first_hash() <= hash &&
            hash <= foo.second_hash()) {
            if( foo.state() == NORMAL) {
                   return foo;
            }
            else {
            // do something else
            }
        }
   }

但是,当我执行程序时它只是挂起...看起来搜索根本不起作用,而且我没有日志告诉我错误在哪里...我做错了什么这里?当我进行线性搜索时,它工作正常,但现在当我尝试改进算法时它失败了......

最佳答案

你的循环条件

for( ; iter != table.end() || iter != table.begin(); --iter )

是无限循环的来源,因为它始终为真。

从评论来看,你想做的是使用反向迭代器:

   map<int,int> a;
   for (int i = 0; i < 100; i++) {
      a[i] = 2*i;
   }
   auto it = a.upper_bound(5);
   reverse_iterator<map<int,int>::iterator> rev_it (it);
   for (; rev_it != a.rend(); rev_it++) {
      cout << rev_it->first;
   }

这将打印 543210

关于c++ - 使用上限和下限在 C++ 映射中找到正确的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15127599/

相关文章:

c++ - libc++ 无法处理 fcgi streambuf

c# - 是否可以在 C# 中获取对字典项的引用?

android-layout - Android 中的拼写检查器

c# - 使用 LINQ select 过滤 Dictionary<string, string>

c++ - C++中按ENTER键后如何继续执行程序?

c++ - 在 iOS 中使用 Objective-C 背后的理念是什么?为什么不是 C++?

c++ - 使用 libarchive 读取目录

python - HTML/CSS 作为 python 脚本的 GUI?

ios - 如何根据唯一属性值对字典数组进行分组?

java - 是否存在 Java 到 C++ 转换器/工具?