【发布时间】:2015-11-25 13:12:11
【问题描述】:
我正在编写一个程序来生成和排序一个随机数数组。 编译器给了我以下错误:
select.cxx: 在函数'void selectionsort(Item*, SizeType) [withItem = int, SizeType = long unsigned int]': select.cxx:95:从这里实例化 select.cxx:16: 错误:没有匹配函数调用‘swap(int*&, long unsigned int&, long unsigned int&)’
这是我的代码:
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
template <class Item, class SizeType>
void selectionsort(Item data[], SizeType n)
{
for (SizeType i = 0; i = n - 2; i++)
{
SizeType j = index_of_minimal(data, i, n);
swap(data, i, j); //data[i] swapped with data[j](minimum)
}
}
template <class Item, class SizeType>
std::size_t index_of_minimal(const Item data[], SizeType i, SizeType n)
{
size_t min = i; //holds index of minimum (initialized to i)
Item t1 = data[i]; //temporary holder for comparing values, initialized as i (starting value)
Item t2; //second holder
for (SizeType j = i++; j = n - 1; j++)
{
t2 = data[j];
if (t2 < t1)
{
t1 = data[j];
min = j;
}
}
return min;
}
template <class Item, class SizeType>
void swap(Item data[], SizeType i, SizeType j) //data[i] swapped with data[j](minimum)
{
Item temp; //holds value to be swapped
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
template <class Item, class SizeType>
void listPrint(Item data[ ], SizeType n)
{
cout << "array:";
for (SizeType i = 0; i = n - 1; i++)
{
cout << " " << data[i];
}
cout << endl;
}
int myrand(int lower, int upper)
{
return (lower + rand() % ( upper - lower + 1 ) );
}
int main()
{
size_t n; //user input
//For random number generator//
srand(time(NULL));
cout << "Please enter a number:" << endl;
cin >> n;
while (n < 1)
{
cout << "Error: please enter a number 1 or larger" << endl;
cin >> n;
}
int rNumbers[n]; //declares int array of size n
int randomN; //to hold randomly generated number
for (size_t i = 0; i < n; i++)
{
randomN = myrand(1, 1000); //generates a random number as randomN
rNumbers[i] = randomN;
}
cout << "Unsorted ";
listPrint(rNumbers, n);
selectionsort(rNumbers, n);
cout << "Sorted ";
listPrint(rNumbers, n);
}
我感觉问题与传递给交换函数的数据类型有关。当main()中声明的n的数据类型为size_t时,为什么错误的第一行指出SizeType = long unsigned int,我也很困惑。
【问题讨论】: