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

不想你离开。 提交于 2020-01-04 06:34:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!