因为将插入排序算法应用于字符串,我遇到了麻烦。我一直在遇到各种错误,我认为这是有关字符串与字符类型的问题。
例如:
candidate template ignored: could not match 'stack' against 'basic_string'
operator> (const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
插入排序算法是从极客那里提取的,但是我只是将其更改为字符串数组。
void insertionSort(string arr[], int n)
{
int i, key, j, unsortedness;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main()
{
//Read in from file stuff missing to save space
int d, lengthStrings, numberStrings; // D will hold the number of data sets
infile >> d;
cout << d << endl;
while (d != 0)
{
infile >> lengthStrings;
infile >> numberStrings;
int numCopy = numberStrings;
int i = 0;
string arrayDna[numberStrings]; //char arrayDna[numberStrings][lengthStrings] instead?;
while (numberStrings != 0)
{
infile >> arrayDna[i];
i++;
numberStrings--;
}
insertionSort(arrayDna[], numCopy);
for (int i = 0; i < numCopy; i++)
cout << arrayDna[i] << "\n";
d--;
所以基本上我需要帮助纠正错误,不允许我将此插入算法应用于自己的字符串数组。
答案 0 :(得分:2)
我没有处理逻辑,但希望清除了所有基本错误:)
更改:
(1)arrayDna[]
=> arrayDna
(在参数中),同时调用insertionSort
函数。
(2)在insertionSort
函数的第key = arr[i]
行中,
key
是int
类型,但需要string
类型,因此将key
的类型从string
更改为int
void insertionSort(string arr[], int n)
{
int i,j, unsortedness;
string key;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
// Since I just need to find unsortedness and not actually sort
//I should probably just replace the two lines with something such as
//unsortedness++ and compare that way
}
arr[j + 1] = key;
}
}
int main(){
//Read in from file stuff missing to save space
int d,lengthStrings, numberStrings; // D will hold the number of data sets
infile >> d;
cout << d << endl;
while(d !=0){
infile >> lengthStrings;
infile >> numberStrings;
int numCopy=numberStrings;
int i=0;
string arrayDna [numberStrings]; //char arrayDna[numberStrings][lengthStrings] instead?;
while(numberStrings != 0){
infile >> arrayDna[i];
i++;
numberStrings--;
}
insertionSort(arrayDna, numCopy);
for (int i = 0; i < numCopy; i++)
cout << arrayDna[i] << "\n";
d--;
}
}