这是我的代码......按字母顺序排序名称的最佳方法是什么?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
string sname[25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++)
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++)
{
cout << sname[output] << endl;
}
system ("pause");
return 0;
}
答案 0 :(得分:3)
标准方法是使用std::sort
:
#include <algorithm>
// ...
std::sort(sname, sname + StudentNum);
默认情况下, std::sort
使用operator<
,这实际上是对字符串进行字母比较。
编辑:的确,它应该是StudentNum
而不是25。