void selectionSort(string [], int);
void showArray(string [], int);
int main()
{
const int SIZE = 20;
string name[SIZE] =
{"Collins, Bill", "Smith, Bart", "Michalski, Joe", "Griffin, Jim",
"Sanchez, Manny", "Rubin, Sarah", "Taylor, Tyrone", "Johnson, Jill",
"Allison, Jeff", "Moreno, Juan", "Wolfe, Bill", "Whitman, Jean",
"Moretti, Bella", "Wu, Hong", "Patel, Renee", "Harrison, Rose",
"Smith, Cathy", "Conroy, Pat", "Kelly, Sean", "Holland, Beth"};
// Show initial order
cout << "The unsorted values are\n";
showArray(name, SIZE);
// Sort the strings
selectionSort(name, SIZE);
// Show ordered order
cout << "The sorted values are\n";
showArray(name, SIZE);
return 0;
}
void selectionSort(string name[], int size)
{
char startScan, minIndex, minValue;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = name[startScan].at(0);
for(int index = startScan + 1; index < size; index++)
{
if (name[index].at(0) < minValue)
{
minValue = name[index].at(0);
minIndex = index;
}
}
name[minIndex] = name[startScan];
name[startScan].at(0) = minValue;
}
}
void showArray(string name[], int size)
{
for (int count = 0; count < size; count++)
cout << name[count] << endl;
cout << endl;
}
我希望这个程序显示未排序的字符串数组,对字符串进行排序,然后显示排序后的数组。相反,它只对名称的第一个字母进行排序。像这样:
未排序的值是
柯林斯,比尔
史密斯,巴特
米哈尔斯基,乔
格里芬,吉姆
桑切斯,曼尼
鲁宾,莎拉
泰勒,蒂龙
约翰逊,吉尔
佳佳,杰夫
莫雷诺,胡安
沃尔夫,比尔
让·惠特曼
莫雷蒂,贝拉
吴红
帕特尔,蕾妮
哈里森,罗斯
史密斯,凯茜
帕特·康罗伊
凯利,肖恩
荷兰,贝丝
排序后的值是
奥林斯,比尔
史密斯,巴特
Cichalski, 乔
格里芬,吉姆
汉切斯,曼尼
莎拉·胡宾
杰勒,蒂龙
凯勒,蒂龙
米思,巴特
米思,巴特
莫尔夫,比尔
让·菲特曼
史密斯,巴特
苏红
git 曼
苏红
蒂特曼·吉恩
沃尔夫,比尔
让·惠特曼
吴红
我觉得我很接近...感谢任何帮助。
最佳答案
如果是学算法的,写这样的代码是可以的。
但是请注意,在“真正的 C++”(即生产代码)中,我们倾向于:
- 使用STL容器代替数组
- 使用 STL 算法而不是原始循环
代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
int main(int argc, char** argv)
{
std::vector<std::string> names =
{
"Collins, Bill", "Smith, Bart", "Michalski, Joe", "Griffin, Jim",
"Sanchez, Manny", "Rubin, Sarah", "Taylor, Tyrone", "Johnson, Jill",
"Allison, Jeff", "Moreno, Juan", "Wolfe, Bill", "Whitman, Jean",
"Moretti, Bella", "Wu, Hong", "Patel, Renee", "Harrison, Rose",
"Smith, Cathy", "Conroy, Pat", "Kelly, Sean", "Holland, Beth"
};
std::sort(names.begin(), names.end(), std::less<>());
std::copy(names.begin(), names.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
链接:
关于C++ 排序字符而不是整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20368663/