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

时间:2015-04-14 03:24:51

标签: c++ arrays sorting

该程序的目的是使用选择排序对字符串数组进行排序。最初,代码中的字符串填充了一个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 are\n";
   showArray(names, NUM_NAMES);

   // Sort the values.
   selectionSort(names, NUM_NAMES);

   // Display the values again.
   cout << "The sorted values are\n";
   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;
   }
} 

1 个答案:

答案 0 :(得分:0)

我添加了.c_str()功能,但它确实有效。我改变了:

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

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