排序数组实现的快速第k个元素

fast kth element of sorted array implementation

本文关键字:元素 数组 实现 排序      更新时间:2023-10-16

我试图从J.F.Sebastian那里理解这个算法,但我试图编译它(gcc/g++ 4.8(得到一个奇怪的编译器错误:

const int n=101,m=31,k=*16-1;
int i;
srand(time(NULL));
for(i=0;i<n;i++)    x[i]=rand();
std::sort(x,x+m,std::greater<float>());
std::sort(x+m,x+n,std::greater<float>());
float v=nsmallest_iter(x,x+m,x+m+1,x+n,n-1-k,std::greater<float>());

编辑

添加我得到的-std=c++11标志:

  from blabla.cpp:2:
blabla.cpp: In instantiation of ‘typename std::iterator_traits<_Iterator>::value_type nsmallest_iter(RandomAccessIterator, RandomAccessIterator, RandomAccessIterator, RandomAccessIterator, size_t, Compare) [with RandomAccessIterator = float*; Compare = std::greater<float>; typename std::iterator_traits<_Iterator>::value_type = float; size_t = long unsigned int]’:
blabla.cpp:58:64:   required from here
blabla.cpp:28:66: error: ‘issorted’ was not declared in this scope
  assert(issorted(firsta,lasta,less) && issorted(firstb,lastb,less));
                                                                  ^
blabla.cpp:28:35: error: ‘issorted’ was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
  assert(issorted(firsta,lasta,less) && issorted(firstb,lastb,less));
                                   ^
blabla.cpp:28:66: note: ‘issorted’ declared here, later in the translation unit
  assert(issorted(firsta,lasta,less) && issorted(firstb,lastb,less));
                                                              ^

有人知道怎么解决这个问题吗?

您使用的是C++11功能,因此您必须使用编译标志

-std=c++11

-std=c++0x

对于第二个问题,您可能缺少一些标头,或者代码有问题。

edit:isorted可能指的是std::is_sorted。它可以在include #include <algorithm> 中找到

std::is_sorted替换issorted
(如果不存在,则添加#include <algorithm>(
(用C++11编译(