gst1502
gst1502

Reputation: 306

Inserting in a multiset: before the first occurence of that value instead of after the last occurence

As the title says multiset inserts a value at the end of the range of all the same values.

(Ex: Inserting 2 in a multiset 1,2,2,3 makes it 1,2,2,/*new*/ 2,3).

How do I get the new value inserted at the start of the range of all the same values?

(Ex: Inserting 2 in multiset 1,2,2,3 should make 1,/*new*/ 2,2,2,3)

Upvotes: 3

Views: 633

Answers (2)

eerorika
eerorika

Reputation: 238351

Use the function insert(iterator hint, const value_type& value) instead of insert(const value_type& value). As per documentation, this will insert before the hint. You can use std::multiset::equal_range to get the iterator to the lower bound.

Upvotes: 2

Midnight Exigent
Midnight Exigent

Reputation: 625

Try this

std::multiset<int> mset { 2,4,5,5,6,6 }; 
int val = 5;
auto it = mset.equal_range ( val ).first; //Find the first occurrence of your target value.  Function will return an iterator

mset.insert ( it, val );  //insert the value using the iterator 

Upvotes: 5

Related Questions