简体   繁体   中英

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

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

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