简体   繁体   中英

Is it possible to do an efficient and partial search of std::map via std::upper_bound?

I have a std::map and two keys key_small, key_big for which I compute the upper_bound . It is known that key_small <= key_big . Here is how I currently do it:

#include <map>
#include <algorithm>

int main() {
  // Some example data
  std::map<int, char> data{{1, 'a'}, {2, 'b'}, {4, 'c'}, {5, 'd'}, {5, 'e'}};
  int key_small = 1,
      key_big = 3; // key_small <= key_big is always true

  auto it_1 = data.upper_bound(key_big);
  auto it_2 = data.upper_bound(key_small);

  // Do something with it_1, then do something with it_2
}

I would like to compute it_1 and it_2 in a more efficient manner. The computation of it_2 above does not take advantage of the fact that I have computed it_1 already. It searches the whole map a second time. My attempt to remedy this is to do the following:

auto it_2 = (it_1 == data.end())
                    ? data.upper_bound(key_small)
                    : std::upper_bound(data.begin(), std::next(it_1), key_small);

The second call seems to ignore the underlying data structure. Thus, it is also inefficient.

Is there a better way of computing it_2 ? It appears to me that finding the second iterator should be possible using log(std::distance(data.begin(), it_1) comparisons. I was told it's possible in a job interview.

I don't care if the solution is only available in c++20. I also accept solutions specific to libstdc++ or libc++. It would be nice if the solution worked with find as well.

Is it possible to do an efficient and partial search of std::map via std::upper_bound?

Although std::upper_bound can be used with non-random access iterators, it has linear complexity with those iterators. So, yes it is possible to do it but whether such linear search is efficient depends on the particular case, and in worst case it will be slower than two std::map::upper_bound lookups.

If distance(it_1, it_2) < log2(N) , then it may be more efficient.

Is there a way to reap the benefits for both ways of computing it_2?

The interface doesn't provide such algorithm. I don't think that any algorithm could have asymptotically better worst case than the two lookups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM