使用选择排序对名称进行排序并显示数据

Sorting names using selection sort and displaying data

本文关键字:排序 显示 数据 选择      更新时间:2023-10-16

该程序的目的是使用选择排序对字符串数组进行排序。最初,代码中的字符串是用 int 数组填充的。我根据说明将其更改为字符串数组。不幸的是,它不能在Visual Studios上运行,但我在Coding Ground上尝试过,它可以工作。代码有什么问题?

#include "stdafx.h"
#include <iostream>
using namespace std;
// Function prototypes
void selectionSort(string [], int);
void showArray(string [], int);
int main()
{
   // Define an array with unsorted values
   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" };
   // Display the values.
   cout << "The unsorted values aren";
   showArray(names, NUM_NAMES);
   // Sort the values.
   selectionSort(names, NUM_NAMES);
   // Display the values again.
   cout << "The sorted values aren";
   showArray(names, NUM_NAMES);
   return 0;
}
//**************************************************************
// Definition of function selectionSort.                       *
// This function performs an ascending order selection sort on *
// array. size is the number of elements in the array.         *
//**************************************************************
void selectionSort(string names[], int size)
{
   int startScan, minIndex; 
   string minValue;
   for (startScan = 0; startScan < (size - 1); startScan++)
   {
      minIndex = startScan;
      minValue = names[startScan];
      for(int index = startScan + 1; index < size; index++)
      {
         if (names[index] < minValue)
         {
            minValue = names[index];
            minIndex = index;
         }
      }
      names[minIndex] = names[startScan];
      names[startScan] = minValue;
   }
}
//**************************************************************
// Definition of function showArray.                           *
// This function displays the contents of array. size is the   *
// number of elements.                                         *
//**************************************************************
void showArray(string names[], int size)
{
   for (int count = 0; count < size; count++)
   {
      cout << names[count] << " ";
      cout << endl;
   }
} 

我添加了.c_str()函数并且它起作用了。我改变了:

    cout << names[count] << " ";

    cout << names[count].c_str() << " ";