c++ - C++中的字符串选择排序

标签 c++ string sorting selection-sort

我的选择排序需要一些字符串方面的帮助。这是我目前所拥有的。

#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;
}
}

如果有人可以帮助我,我将不胜感激。

最佳答案

minValue = array[startScan];

您正在将一个字符串分配给一个整数。将 minValue 的类型设为 string。那么它应该可以工作。

关于c++ - C++中的字符串选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23333220/

相关文章:

c++ - 可变大小的对象初始化

c++ - 无法在 linux (i686-w64-mingw32-g++) 上交叉编译包含 sqlite 的 c++ 类(未定义引用)

c++ - 在 c++ builder 中启动时打开两个窗体

c++ - 让用户创建自己的类实例

algorithm - 外部合并排序算法如何工作?

Python - 如何将 IF 语句转换为函数以使用其他字符串多次调用?

string - flutter 中的拆分字符串

java - 我可以向 String 类添加新方法吗?

linux - 如何在其包含的时间间隔内对文本文件中的项目进行排序

c - 为什么每次迭代时冒泡排序都不能正确打印?