【问题标题】:Inserting in a multiset: before the first occurence of that value instead of after the last occurence插入多重集:在该值第一次出现之前而不是在最后一次出现之后
【发布时间】:2019-12-07 18:48:13
【问题描述】:

正如标题所说,multiset 在所有相同值范围的末尾插入一个值。

(例如:在多重集中插入​​ 2 1,2,2,3 使其成为 1,2,2,/*new*/ 2,3)。

如何在所有相同值范围的开头插入新值?

(例如:在多重集 1,2,2,3 中插入 2 应为 1,/*new*/ 2,2,2,3

【问题讨论】:

  • 你不能反转整个多重集吗? std::multiset<int, greater<int>> 并使用 reverse_iterator 进行迭代?
  • 好吧,鉴于它还有其他用途,我认为这不是一个好的解决方案。 @Jarod42
  • 更好的例子是std::pair<ValueType, IdType> 只比较ValueTypeint,这并不重要。

标签: c++ stl multiset


【解决方案1】:

试试这个

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】:

    使用函数insert(iterator hint, const value_type&amp; value) 代替insert(const value_type&amp; value)。根据文档,这将在hint 之前插入。您可以使用std::multiset::equal_range 使迭代器到达下限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2017-01-25
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多