【发布时间】:2018-02-23 21:01:56
【问题描述】:
我有一个插入排序函数
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
【问题讨论】:
-
/OT:不要使用过时的
throw说明符,它们不会做任何其他事情,也不会强制执行,因此使用它们几乎没有意义。 -
1.最有可能来自
int temp = this->items[from];2. 会是来自编译器的奇怪错误消息。 -
不应该将
temp声明为TYPE,而不是硬编码为int?而且不需要初始化它,因为它是在下一行分配的。 -
您的
insertionSort函数适用于ArrayList对象的副本,因此您对本地对象进行排序,调用此函数后传递的对象没有改变。 -
@Mykel 我们需要看到更多的类实现。如果构造函数使用
new,那么在析构函数中使用delete是正确的,但是您对副本所做的更改不会影响原始文件。如果构造函数不使用new,那么你不应该在析构函数中使用delete。
标签: c++ templates overloading operator-keyword