Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中查找正确的条目+;使用上下限映射_C++_Map - Fatal编程技术网

C++ 在C+中查找正确的条目+;使用上下限映射

C++ 在C+中查找正确的条目+;使用上下限映射,c++,map,C++,Map,我正试图通过使用上限函数在C++map中优化搜索: map是变量表: 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

我正试图通过使用
上限
函数在
C++
map
中优化搜索:
map
是变量

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
            }
        }
   }
Foo&search(uint64 id,uint64散列){
std::map::const_迭代器iter;
std::对密钥(id,散列);
iter=表的上限(键);
//为了完整性,我搜索可能匹配的元素
//它们可能属于不同的散列范围
对于(;iter!=table.end()| | iter!=table.begin();--iter){
const-Foo-Foo=iter->second;
如果(foo.id()==foo.first_hash()您的循环条件

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;
   }
map a;
对于(int i=0;i<100;i++){
a[i]=2*i;
}
自动it=a.上限(5);
反向迭代器rev_it(it);
for(;rev_it!=a.rend();rev_it++){
cout优先;
}

这将打印
543210

true-true…但是我正在丢失第一个元素,不是吗?因为稍后我运行测试用例,其中一些失败。但是,我不想跳出for循环。直到
table.end()我才递增
…所以我需要停止我的for循环。也许我不太明白你在做什么。
上限
返回一个迭代器到某个元素,然后你想反向迭代集合直到开始?是的。假设我的地图上有
'a','b','c','d'
。我在上限上查找
'b'
,然后它返回给我
'c'
对吗?但是,因为有两个哈希键,
'a',b'
将是候选项,所以我必须检查它们。@philippe啊!那么我想我有一个解决方案给你。检查我的编辑。这个表达式是什么
foo.id()==foo.first\u hash()