-1

I want to find no of elements present in set before the lower bound of an given element,I thought of using pointer arithmetic with std::set::iterators since they behave like pointer, here is what I tried:

set<int>q;
set<int>::iterator curr;
set<int>::iterator strt;
l = num.size();
q.insert(num[l-1]);
strt = q.begin();
temp = 1;
int x;
for(int i=l-2;i>=0;i--)
{
    curr = q.lower_bound(num[i]);
    if(curr == q.end())
        stats.push_back({temp,0});
    else
    {
        x = curr-strt;//ERROR
        stats.push_back({x,temp-x});
    }
    q.insert(num[i]);
    temp++;
}

is there is any way find no of elements present in set before the lower bound of an given element?

Sab
  • 485
  • 5
  • 17

2 Answers2

1

You'll have to iterate through the set from the beginning to the point you've found to count the number of elements. There's a library function for that:

x = std::distance(strt, curr);

Arithmetic like curr-strt is only defined for random access iterators, where the calculation can be done in constant time. Functions like distance will work for more general iterator types, but might be slow if the iterator doesn't directly support that operator.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • That a `O(n)`, is there any other method with lesser time complexity or is there any more suitable container? – Sab May 25 '15 at 15:20
  • @Sab: Depending on what else you're doing, a sorted array/vector might be better. You can use `std::lower_bound` etc. to search in logarithmic time, and find iterator distances in constant time. Maintaining the sorted order might need more work. – Mike Seymour May 25 '15 at 15:21
  • @MikeSeymour It's important to note that "You'll have to iterate through the set from the beginning to the point you've found" is not a property of balanced trees in general, just STL trees in particular. You might want to see my answer below. – Ami Tavory May 25 '15 at 15:24
1

Using data structure augmentation, it's possible to do dynamic order statistics in logarithmic time.

I've written once a libstdc++ extension for this, and later on mad a python version.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185