现在我又收到了另一个错误。
error C2065: 'temp' : undeclared identifier
我知道对于temp
我需要声明类似int temp[]
的数组类型,
但如果我不知道它是什么呢?
它可以是int
或string
或double
。
如何在不指定类型的情况下创建临时数组?
我添加了我的Mergesort功能。
这是我的代码:
template<class T>
void Mergesort(T& a, int first, int last);
template<class T>
void Merge(T& a, int first, int last);
int main()
{
int num;
cout << "How many words? ";
cin >> num;
Array<string> b(num);
cout << "Enter the " << num << " words below:\n";
for (int i=0; i<num ; i++)
cin >> 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<class T>
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<class T>
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&);
};
答案 0 :(得分:4)
T a[]
表示您期望一个T
数组作为参数类型 - 但这是一个C数组,而不是类类型。您的类模板Array
就是这样 - 一个类模板只会通过operator[]()
方便地访问其内容。
将第一个错误更改Quicksort()
签名修复为:
template<class T>
void Quicksort(T& a, int first, int last)
然后存在使用T
作为局部变量pivot
的问题。为了通常使用容器,为容器的包含类型(值)提供名为typedef
的{{1}}或多或少是标准的:
value_type
根据该惯例,您可以如下声明template<class T>
class Array
{
public:
typedef T value_type;
// ...
};
:
pivot