У меня есть сортировка слиянием, и она будет работать, когда я
mergeSort<int>(val_array1,numValues);
, но как только я изменю ее на float
mergeSort<float>(val_array2,numValues);
, я получаю эту ошибку:
1>c:\users\cbadau\documents\visual studio 2010\projects\lab\lab\lab12.cpp(71): error C2782: 'void recMergeSort(ItemType [],ItemType,ItemType)' : template parameter 'ItemType' is ambiguous
1> c:\users\cbadau\documents\visual studio 2010\projects\lab\lab\lab12.cpp(58) : see declaration of 'recMergeSort'
1> could be 'int'
1> or 'float'
1> c:\users\cbadau\documents\visual studio 2010\projects\lab\lab\lab12.cpp(96) : see reference to function template instantiation 'void mergeSort<float>(ItemType [],int)' being compiled
1> with
1> [
1> ItemType=float
1> ]
1>
Исходный код:
#include<iostream>
using namespace std;
template<class ItemType>
void merge(ItemType list[], ItemType first, ItemType last, ItemType mid)
{
ItemType arraySize = last - first + 1;
ItemType* tempList = new ItemType[arraySize];
ItemType beginPart1 = first;
ItemType endPart1 = mid;
ItemType beginPart2 = mid + 1;
ItemType endPart2 = last;
int index = 0;
while (beginPart1 <= endPart1 && beginPart2 <= endPart2) {
if (list[beginPart1] < list[beginPart2]) {
tempList[index] = list[beginPart1];
beginPart1++;
}
else {
tempList[index] = list[beginPart2];
beginPart2++;
}
index++;
}
while (beginPart1 <= endPart1) {
tempList[index] = list[beginPart1];
index++;
beginPart1++;
}
while (beginPart2 <= endPart2) {
tempList[index] = list[beginPart2];
index++;
beginPart2++;
}
for (int i = first; i <= last; i++) {
list[i] = tempList[i - first];
}
delete[] tempList;
}
template<class ItemType>
void recMergeSort(ItemType list[], ItemType first, ItemType last)
{
if (first < last) {
ItemType mid = (first + last) / 2;
recMergeSort(list, first, mid);
recMergeSort(list, mid + 1, last);
merge(list, first, last, mid);
}
}
template<class ItemType>
void mergeSort(ItemType list[], int length)
{
recMergeSort(list, 0, length - 1);
}
int main()
{
int val_array1[] = {43, 7, 10, 23, 38, 4, 19, 51, 66, 14};
float val_array2[] = {43.2, 7.1, 10.5, 3.9, 18.7, 4.2, 19.3, 5.7, 66.8, 14.4};
int numValues = 10;
cout<<"val_array1 unsorted: "<<endl;
for(int i = 0; i <numValues; i++)
{
cout<<val_array1[i]<<endl;
}
cout<<"val_array2 unsorted: "<<endl;
for(int x=0; x <numValues; x++)
{
cout<<val_array2[x]<<endl;
}
mergeSort<int>(val_array1,numValues);
mergeSort<float>(val_array2,numValues);
cout<<"val_array1 sorted: "<<endl;
for(int y = 0; y <numValues; y++)
{
cout<<val_array1[y]<<endl;
}
cout<<"val_array2 sorted: "<<endl;
for(int t=0; t <numValues; t++)
{
cout<<val_array2[t]<<endl;
}
system("pause");
return 0;
}
Есть идеи по поводу проблемы?