RuLoViC
RuLoViC

Reputation: 855

Position when inserting in std::map

I have a method which inserts a pair in std::map. The map is something like (0, value0), (3, value3), (8, value8) ... So when I insert I need to specify the integer value. My problem is that if I have: (0, value0), (3, value3) and I want to insert (5, value5) with value3 same as value5 the pair (5, value5) must not be inserted. How could I check that the previous position to the position where my element should go does not have same value? So far I have tried to insert the pair, get the iterator, check previous value and remove the inserted value if needed. But I find that solution kind of ugly. Any ideas? Thanks in advance

Upvotes: 0

Views: 614

Answers (1)

Alan Stokes
Alan Stokes

Reputation: 18974

Map's lower_bound function will return an iterator to the first element whose position is greater than or equal to the one you give it; then you can go back one. (Carefully, in case you're already at the start.)

http://en.cppreference.com/w/cpp/container/map/lower_bound

Upvotes: 2

Related Questions