Sai Teja T
Sai Teja T

Reputation: 370

Index of the lower_bound of a value in sets and maps in c++

Suppose I want to get the index of the lower_bound of a value in a set and if i type

cout<<set.lower_bound(number)-set.begin()<<endl;

It is showing an error: no match for ‘operator-’

The same goes for maps as well,

However for arrays and vectors if i use

lower_bound(begin,end,val)-begin 

it is showing the index

Why is that?

Upvotes: 0

Views: 4149

Answers (1)

asmmo
asmmo

Reputation: 7100

Yes, this because the operator - is not defined for the iterators of std::sets (bidirectional iterators) while it's defined for the arrays iterators (random access iterators).

Instead, you can use std::distance(), as follows

int main()
{
    std::set<int> set {1, 2, 4, 5, 6};
    int number = 3;
    std::cout<<std::distance(set.begin(), set.lower_bound(number))<<std::endl;
}

And note that your sets will be ordered. I don't know what u expect.

And as john said there might be a design flaw. maybe you choose the wrong container for your purpose.

Upvotes: 5

Related Questions