现在我得到另一个错误..错误C2065:'temp':未声明的标识符我知道对于temp我需要声明数组类型如int temp []但是如果我不知道它是什么...它可能是int for string或double ..我怎样才能创建一个临时数组而不指定它应该是什么
我添加了一个mergesort函数 .
这是我的代码:
template
void Mergesort(T& a, int first, int last);
template
void Merge(T& a, int first, int last);
int main()
{
int num;
cout << "How many words? ";
cin >> num;
Array b(num);
cout << "Enter the " << num << " words below:\n";
for (int i=0; i> b[i];
cout << "\nThank you!!\n";
// Copy the original array and sort it using Quicksort
Array<string> bq(b);
Quicksort(bq, 0, num-1);
cout << "\nElements sorted using quicksort:\n";
for (int i=0; i<num ; i++)
cout << bq[i]<< " ";
cout << "\n";
Array<string> bm(b);
Mergesort(bm, 0, num-1);
cout << "\nElements sorted using mergesort:\n";
for (int i=0; i<num ; i++)
cout << bm[i]<< " ";
cout << "\n";
template
void Mergesort(T& a, int first, int last)
{
if (first < last)
{
int mid = (first + last) / 2;
Mergesort(a, first, mid);
Mergesort(a, mid+1, last);
Merge(a, first, last);
}
}
template
void Merge(T& a, int first, int last)
{
int mid = (first + last) / 2;
int one = 0, two = first, three = mid + 1;
while (two <= mid && three <= last) // Neither sublist is done
if (a[two] < a[three]) // Value in first half is smaller
temp[one++] = a[two++];
else // Value in second half is smaller
temp[one++] = a[three++];
while (two <= mid) // Finish copying first half
temp[one++] = a[two++];
while (three <= last) // Finish copying second half
temp[one++] = a[three++];
for (one = 0, two = first; two <= last; a[two++] = temp[one++]);
}
//ARRAY.h
using namespace std;
template<class T> class Array
{
public:
Array(int s);
Array(int l, int h);
Array(const Array& other);
~Array();
T& operator[](int index);
const T& operator[](int index) const;
int get_size() const {return arraySize;}
private:
int low;
int high;
int arraySize; //size of array
int offset; //to adjust back to an index of zero
T *array_;
void Copy(const Array&);
};
1 回答
T a[]
表示您期望T
数组作为参数类型 - 但这是一个C数组,而不是类类型 . 您的类模板Array
只是一个类模板,它恰好通过operator[]()
提供对其内容的便利访问 .要将第一个错误更改
Quicksort()
s签名修复为:然后有一个问题是你使用
T
作为局部变量pivot
. 为了通常使用容器,为容器的包含类型(值)提供名为value_type
的typedef
或多或少是标准的:根据该约定,您可以如下声明
pivot
: