字符串选择以C ++排序 [英] String Selection Sort in C++

查看:141
本文介绍了字符串选择以C ++排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要一些字符串帮助我的选择排序。这是我到目前为止。

Need some help with string for my selection sort. Here's what I have so far.

#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更改为字符串。

Updated my code and it works perfect. Changed minValue from int to 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;
}
}

如果有人可以帮助我,赞赏。

If someone can help me out here that would be greatly appreciated.

推荐答案

minValue = array[startScan];

您正在为int分配一个字符串。将 minValue 的类型设置为 string 。那么它应该工作。

You are assigning a string to an int. Make the type of minValue as string. Then it should work.

这篇关于字符串选择以C ++排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆