问题
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
)
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/57270605/inserting-in-a-multiset-before-the-first-occurence-of-that-value-instead-of-aft