std::partition segfault issue



只是为了好玩,我使用std::partition()实现了快速排序,并遇到了段错误。 我在这里找到了一个示例实现,它只是略有不同并且有效。 虽然我可以看到它们在实施效率方面的优势,但我不明白为什么我的会出现段错误。 唯一的区别是我没有做第二个std::Partition来避免传递与以后递归调用的透视相同的值。 任何人都可以发现我的问题吗?

#include <algorithm>
#include <vector>
#include <iostream>
template <typename iter> void quick_sort(iter first, iter last)
{
if ( std::distance( first, last ) <= 1 )
{
return;
}
auto pivot = *std::next( first, std::distance( first, last ) / 2 );
#if 0 //works
iter midpoint1 = std::partition( first, last, [pivot](const auto& x)->bool{ return ( x < pivot ); } );
iter midpoint2 = std::partition( midpoint1, last, [pivot](const auto& x)->bool{ return !( pivot < x ); } );
quick_sort( first, midpoint1 );
quick_sort( midpoint2, last );
#else //segfaults
iter midpoint = std::partition( first, last, [pivot](const auto& x){ return ( x < pivot ); } );
quick_sort( first, midpoint );
quick_sort( midpoint, last );
#endif
}
int main()
{
std::vector<int> to_sort = {2,1,7,4,6,9,2,1,5,8,9,4,7,4,3,7,4,8,3,8,9};
quick_sort( std::begin( to_sort ), std::end( to_sort ) );
for ( auto n : to_sort )
{
std::cout << n << ',';
}
std::cout << 'n' << std::flush;
}

考虑一个序列,其中您选择的枢轴是最小的元素。

然后,您的分区将导致一个空序列(您停止递归(和原始序列。

重复直到堆栈溢出,或者通过尾部调用优化,系统磨损。

顺便说一句,在您所说的代码中,您曾经使用过较大的>,尽管您应该只使用较小的<

最新更新