1

I am trying to use Binary search function provided by STL which requires a vector to be sorted first. So that's why I am trying to directly use Set so i don't have to sort first.

But when used set in the following way,

`

#include <bits/stdc++.h>
using namespace std;
int main(){
set <int> mn = {11, 33, 44, 66, 80,90};
auto it= mn.lower_bound(55);
cout<<it-mn.begin();
    return 0;
}

`

an error occurs saying:

error: no match for ‘operator-’ (operand types are ‘std::_Rb_tree_const_iterator’ and ‘std::set::iterator’

How to use set to get index number of returned iterator here?

PS: I have also tried using set::lower_bound, but shows the same error.

jongla
  • 113
  • 1
  • 5

3 Answers3

2

The iterators for set are bidirectional iterators, which means that you can't subtract two of them.

You can calculate the distance thus: std::distance(mn.begin(), it) but you need to be aware that for bidirectional iterators, this is an O(N) operation - not constant time.

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • usually the time complexity for a sorted array is O(n) + O(n * log(n)) for vector vs O(n * log(n)) for using set, but in this case as I have to use std::distance, the complexity would be the same for both, so no benefit in using set instead of vector, is this correct? – jongla Jan 25 '20 at 05:01
  • @jongla Correct. Also, the `set` has to do a lot of allocations and pointer chasing, so the `vector` should be *way* faster. Also, *constructing* the set is `O(n * log(n))`, so `vector` is *waaaay* faster. – Mooing Duck Sep 01 '23 at 15:51
0

I was also stuck in a similar problem, so I used the sorted vector instead of a set and performed the operation (it - v.begin()).

0

Cause it based on a tree you cannot just randomly subtract the beginning from it. A vector for example is a linear Data structure which mean you can apply this kind of operation on it.

If you want to do this operation you can use Ordered_set then. You can found it in gnu_pbds namespace.

Here is a link for it: https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds/

  • Notes: (1) That ordered set container is not part of the C++ Standard library. (2) The Geeks-for-Geeks website generally gets quite a poor reception, here on Stack Overflow. – Adrian Mole Sep 02 '23 at 05:14