【发布时间】:2014-06-13 12:50:30
【问题描述】:
在我的选择排序中需要一些关于字符串的帮助。这是我目前所拥有的。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//Constant globals
const int NUM_NAMES = 20;
//Function protoypes
void selectionSort(string [], int);
void showArray(const string [] , int);
int main()
{
string names[NUM_NAMES] = {"Collins, Bill", "Smith, Bart", "Allet, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
"Taylor, Terri", "Johnson, Jill",
"Aliison, Jeff", "Weaver, Jim", "Pore, Bob",
"Rutherford, Greg", "Javens, Renee",
"Harrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth"};
char again; //Hold y to repeat
do
{
//Show array
cout << "The unsorted values are\n";
showArray(names, NUM_NAMES);
//Sort array
selectionSort(names, NUM_NAMES);
//Display sorted array
cout << "The sorted values are\n";
showArray(names, NUM_NAMES);
//Run program again?
cout << "Would you like to run the program again? (Y/N): ";
cin >> again;
}while(again == 'y' || again == 'Y');
return 0;
}
更新了我的代码,它运行良好。将 minValue 从 int 更改为 string。
void selectionSort(string array[], int NUM_NAMES)
{
int startScan, minIndex;
string minValue;
for(startScan = 0; startScan < (NUM_NAMES -1); startScan++)
{
minIndex = startScan;
minValue = array[startScan];
for(int index = startScan +1; index < NUM_NAMES; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
}
如果有人可以在这里帮助我,将不胜感激。
【问题讨论】:
-
您的
selectionSort函数是否为integers工作?如果它不适用于整数,那么我建议您在转到字符串版本之前修复它 -
string 具有比较方法和重载运算符。一旦它适用于整数,您就可以替换字符串的方法/运算符。并明确将 minValue 声明为字符串类型变量。
标签: c++ string sorting selection-sort