c++ STL 算法set_union和sort

灵活使用STL中的相关算法,对C++开发是必备的,这里记录下最近用到的两个STL算法。

1.set_union

合并集合S1US2,得到并集,这里有个前提是S1和S2是set集合的迭代器,这就意味着这些集合是排过序的

,可以有重复值,这就可以接受set\multiset作为参数;

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator set_union (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2, InputIterator2 last2,
                            OutputIterator result)
{
  while (true)
  {
    if (first1==last1) return std::copy(first2,last2,result);
    if (first2==last2) return std::copy(first1,last1,result);

    if (*first1<*first2) { *result = *first1; ++first1; }
    else if (*first2<*first1) { *result = *first2; ++first2; }
    else { *result = *first1; ++first1; ++first2; }
    ++result;
  }
}

2.sort函数

只接受vector和deque的传参,因为关系型容器(map,set)底层是由红黑树实现的,自带排序功能,并不需要

我们再排序,序列容器中的(stack,queue,priority-queue)都有特定的出入口,不允许用户对元素进行排序;

当我们自己定义比较方式传给sort时,要注意到sort是strict weak order,

”Binary function that accepts two elements in the range as arguments, and returns a value convertible tobool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.This can either be a function pointer or a function object.”

如果,当两个元素相等时,返回的结果是true,就会导致程序在sort处会出现不可预期的coredump;这是由于底层的sort实现,导致这个问题。

有时间贴下代码验证下。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值