【发布时间】:2023-03-03 02:50:02
【问题描述】:
我正在尝试了解选择排序如何与字符串一起使用。
这是我目前所拥有的:
#include <iostream>
#include <string>
using namespace std;
// Prototypes
void selectionSort(string arr[], int size);
void showArray(string arr[], int size);
int main() {
const int NUM_NAMES = 20;
string names[NUM_NAMES] = {"Collins, Bill", "Smith, Bart", "Allen, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
"Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
"Looney, Joe", "Wolfe, Bill", "James, Jean",
"Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
"Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth"};
// Insert your code to complete this program
cout << "The names on the list in no particlular order are: ";
showArray(names, NUM_NAMES);
// Calling the sorted array
selectionSort(names, NUM_NAMES);
// Displaying sorted array
cout << "The names in sorted order are: ";
showArray(names, NUM_NAMES);
return 0;
}
// Function to sort the string
void selectionSort(string arr[], int size) {
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minValue = arr[startScan];
for (int index = (startScan + 1); index < size; index++) {
if (arr[index] < minValue) {
minValue = arr[index];
minIndex = index;
}
}
arr[minIndex] = arr[startScan];
arr[startScan] = minValue;
}
}
// Function to display the array's conents
void showArray(const int arr[], int size) {
for (int count = 0; count < size; count++) {
cout << arr[count];
cout << "\t\n";
}
}
如果我尝试构建它,它会失败并收到一条错误消息。 "调用 'selectionSort' 没有匹配的函数。"
但是,如果我尝试使用整数而不是字符串,我可以让它正确编译和排序。
#include <iostream>
#include <string>
using namespace std;
// Prototypes
void selectionSort(int [], int);
void showArray(const int [], int);
int main() {
const int NUM_NAMES = 8;
int names[NUM_NAMES] = {1,3,5,7,3,5,7,9};
// Insert your code to complete this program
cout << "The names on the list in no particular order are: ";
showArray(names, NUM_NAMES);
// Calling the sorted array
selectionSort(names, NUM_NAMES);
// Displaying sorted array
cout << "The names in sorted order are: ";
showArray(names, NUM_NAMES);
return 0;
}
// Function to sort the string
void selectionSort(int array[], int size) {
int startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++) {
minIndex = startScan;
minValue = array[startScan];
for (int index = (startScan + 1); index < size; index++) {
if (array[index] < minValue) {
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
// Function to display the array's contents
void showArray(const int array[], int size) {
for (int count = 0; count < size; count++) {
cout << array[count];
cout << "\t\n";
}
}
我不太确定字符串排序在哪里出错。 Image of c++ program with the portion that has an issue
【问题讨论】:
标签: c++ arrays string sorting selection-sort