[英]Sorting doesn't work with templated class
我有一个插入排序功能
void insertionSort(ArrayList<int> myData)
{
for (int i = 1; i < myData.getSize(); i++) {
int index = myData[i];
int j = i;
while (j > 0 && myData[j-1] > index) {
myData.swap(j - 1, j);
j--;
}
myData[j] = index;
}
}
使用此交换功能
template<class TYPE>
void ArrayList<TYPE>::swap(int from, int to) throw(std::out_of_range)
{
int temp = 0;
temp = this->items[from];
this->items[from] = this->items[to];
this->items[to] = temp;
swapNum++;
}
这就是我的私有方法的样子
TYPE * items;
int currentLength;
static int swapNum;
我有一个重载的 [] 运算符和一个 getSize() 函数,我认为我写得很好并且不会导致我的问题。 现在,如果我在 main.cpp 中执行此操作
ArrayList<int>m_Data(1);
并在 m_Data 上附加说 4,2,9,1 并调用
insertionSort(m_Data);
我有两个错误
1. Error C2440 '=': cannot convert from 'std::string' to 'int'
关于交换函数和
2. The insertion sort doesn't work
第一个问题:它应该类似于TYPE temp = this->items[from]
。 修复后(我使用 STL 交换)功能工作。 嗯,它适用于 STL 向量和交换。 如果您仍然有问题,那么您的数组结构可能无效。
编辑:在函数“insertionSort”中,你不应该有模板(如交换函数)吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.