【发布时间】:2019-12-03 19:48:15
【问题描述】:
我不知道为什么代码不适用于浮点类型,我的意思是 qsort 算法。我尝试了不同的方法对其进行排序,但没有成功。在 int 类型的情况下,代码可以正常工作,但不适用于浮点类型,这让我感到困惑。有谁知道是什么问题?
感谢 tpps。
标题:
template <class T>
class arraysort
{
public:
arraysort(int);
~arraysort();
//int compare (const void *a,const void *b);
T& operator[] (int index);
void quicksort(T a, T b);
void printout();
private:
T *ptr;
int size;
const void *a;
const void *b;
static T compare (const void * a, const void * b);
};
c++
#include "arraysort.h"
#include <stdlib.h>
template <typename T>
arraysort<T>::arraysort(int s)
{
size = s;
ptr = new T[size];
}
template <typename T>
arraysort<T>::~arraysort()
{
delete [] ptr;
}
template <typename T>
T& arraysort<T>::operator[](int index)
{
return ptr[index];
}
template <typename T>
T arraysort<T>:: compare (const void * a, const void * b)
{
T fa = * (const T * ) a;
T fb = * (const T * ) b;
return (fb - fa);
}
template <typename T>
void arraysort<T>::quicksort (T a, T b)
{
qsort(ptr, size, sizeof(T), (int( * )(const void * ,const void * )) compare);
}
template <typename T>
void arraysort<T>::printout()
{
for(int i = 0; i < size; i++)
std::cout<< ptr[i] <<" ";
std::cout<<std::endl;
}
【问题讨论】:
-
为什么在 C++ 中使用
qsort,而我们有更好的接口的std::sort? -
您忘记显示您是如何尝试使用它的以及您遇到了哪些编译错误。
-
已经使用
std::sort.. -
这也可能有问题,因为templates should be defined in the header.