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

玛丽

该程序的目的是使用选择排序对字符串数组进行排序。最初,代码中的字符串填充有一个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;
   }
} 
Ganesh Kamath-“疯狂代码”

我添加了.c_str()功能,它起作用了。我变了:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章