Sorting alphabetically
Here is my code...What would be the best way to sort names alphabetically?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
s开发者_StackOverflow中文版tring 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;
}
The standard way is to use std::sort
:
#include <algorithm>
// ...
std::sort(sname, sname + StudentNum);
std::sort
uses operator<
by default, which actually does an alphabetical comparison for strings.
EDIT: Indeed, it should be StudentNum
instead of 25.
精彩评论