[英]Sorting doesn't work with templated class
I have an insertion sort function我有一个插入排序功能
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;
}
}
which uses this swap function使用此交换功能
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++;
}
This is how my private methods look like这就是我的私有方法的样子
TYPE * items;
int currentLength;
static int swapNum;
I have an overloaded [] operator and a getSize() function that I think I wrote well and not contributing to my problem.我有一个重载的 [] 运算符和一个 getSize() 函数,我认为我写得很好并且不会导致我的问题。 Now if I do this in my main.cpp
现在,如果我在 main.cpp 中执行此操作
ArrayList<int>m_Data(1);
and append say 4,2,9,1 on the m_Data and call并在 m_Data 上附加说 4,2,9,1 并调用
insertionSort(m_Data);
I get two errors我有两个错误
1. Error C2440 '=': cannot convert from 'std::string' to 'int'
on the swap function and关于交换函数和
2. The insertion sort doesn't work
First problem: it should be something like TYPE temp = this->items[from]
.第一个问题:它应该类似于
TYPE temp = this->items[from]
。 After repairing it (I used STL swap) function works.修复后(我使用 STL 交换)功能工作。 Well, it works on STL vector and swap.
嗯,它适用于 STL 向量和交换。 If you still do have problem, then your array structure is probably invalid.
如果您仍然有问题,那么您的数组结构可能无效。
EDIT: In function 'insertionSort' shouldn't you have template (as in swap function)?编辑:在函数“insertionSort”中,你不应该有模板(如交换函数)吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.