【问题标题】:Sorting names using selection sort and displaying data使用选择排序对名称进行排序并显示数据
【发布时间】:2015-04-14 03:24:51
【问题描述】:

程序的目的是使用选择排序对字符串数组进行排序。最初,代码中的字符串是用一个 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;
   }
} 

【问题讨论】:

  • 你不见了#include &lt;string&gt;

标签: c++ arrays sorting


【解决方案1】:

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

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

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

【讨论】:

  • 感谢代码狂潮。我不敢相信我忘了检查我的头文件。
猜你喜欢
  • 2014-01-14
  • 2021-06-13
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多