我一直在尝试编写气泡排序程序,在该程序中,用户输入数组大小,然后计算机为数组的所有值生成随机数。之后,程序会询问用户是否要以升序或降序对数组进行排序。之后,它会进行气泡排序。我收到错误消息:
我知道这是一个链接器错误,但我不知道是什么。谁能解释我的错误以及如何解决?
这是代码:
#include <iostream>
#include <ctime> // for time()
#include <cstdlib> // for srand() and rand()
#include <algorithm>// for swap()
using namespace std;
typedef bool (*pfPointer) (int, int);
void ArraySorter(int, int, pfPointer);
bool Ascending(int, int);
bool Descending(int, int);
int main() {
cout << "Enter the size of the array: ";
int nArraySize;
cin >> nArraySize;
int *pnArray = new int [nArraySize];
srand(static_cast<int>(time(0)));
cout << "Do you want your array to sort in ascending or descending order (a/d)? ";
char nUserSort;
cin >> nUserSort;
cout << '\n';
if (nUserSort == 'a')
ArraySorter(pnArray[nArraySize], nArraySize, Descending); //This allows the user to decide whether they want an ascending or descending function
else
ArraySorter(pnArray[nArraySize], nArraySize, Ascending);
//This prints out the array
for(int qqq = 0; qqq < nArraySize - 1; qqq++)
{
cout << pnArray[qqq] << " || ";
}
cout << pnArray[nArraySize - 1] << endl;
delete [] pnArray;
return 0;
}
void ArraySorter(int pnArray[], int nArraySize, pfPointer pComparison)
{
//Assigns a random number to each value in the array pnArray
for (int iii = 0; iii< nArraySize; iii++)
{
pnArray[iii] = rand();
}
// Will change the starting index of the array each time the loop runs through
for (int nStartIndex = 0; nStartIndex < nArraySize; nStartIndex++)
{
// Declares a variable to find the location of the smallest variable in the array
int nSmallestIndex = nStartIndex;
// Runs through each array value and finds the smallest one, then registers it
for (int nCurrentIndex = nSmallestIndex +1; nCurrentIndex < nArraySize; nCurrentIndex++)
{
// If the current array value is less than the starting array value, it will log it's location in the array in nSmallestIndex
if (pComparison(pnArray[nCurrentIndex] , pnArray[nSmallestIndex]))
{
nSmallestIndex = nCurrentIndex;
}
}
//Switches the smallest value with the starting value
swap(pnArray[nStartIndex], pnArray [nSmallestIndex]);
}
}
bool Ascending(int nValue1, int nValue2)
{
return nValue1 < nValue2; //Will sort the variables from smallest to greatest
}
bool Descending(int nValue1, int nValue2)
{
return nValue1 > nValue2; //Will sort the variables from greatest to smallest
}
附言我正在运行XCode 6.1.1
最佳答案
ArraySorter
的函数原型(prototype)采用(int, int, pfPointer)
,但函数定义采用(int [], int, pfPointer)
。
将ArraySorter
的原型(prototype)更改为(int [], int, pfPointer)
,并将对ArraySorter
的调用更改为ArraySorter(pnArray, nArraySize, Descending)
而不是ArraySorter(pnArray[nArraySize], nArraySize, Descending)
。