std::sort引起的core

  1. /// This is a helper function...
  2.   template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
  3.     _RandomAccessIterator
  4.     __unguarded_partition(_RandomAccessIterator __first,
  5.              _RandomAccessIterator __last,
  6.              const _Tp& __pivot, _Compare __comp)
  7.     {
  8.       while (true)
  9.     {
  10.      while (__comp(*__first, __pivot))
  11.      ++__first;
  12.      --__last;
  13.      while (__comp(__pivot, *__last))
  14.      --__last;
  15.      if (!(__first < __last))
  16.      return __first;
  17.      std::iter_swap(__first, __last);
  18.      ++__first;
  19.     }
  20.     }

此函数完成快速排序中分区功能,即将比哨兵小的数据放在其前,大的放在其后。

函数中使用的是
while (__comp(*__first, __pivot))
    ++__first;

如果当比较元素相同返回真时,此时比较元素将会继续向下遍历,在极端情况下,例如程序中所有元素都是一样的情况下,在这种情况下,就会出现访问越界,结果就是导致程序出现segment fault

所以在写c++ stl中的比较函数是,bool返回真的时候,一定是“真的”大,或者小,等于的时候只能返回false。

猜你喜欢

转载自eric-gcm.iteye.com/blog/2414234
std