2011-04-01 261 views
0

这是我的代码...按字母顺序排序名称的最佳方法是什么?按字母顺序排序

#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; 
} 
+2

阵列in C++从'0'编号为'的N- 1'。你的第一个'for'应该说:'for(int i = 0; i Pablo 2011-04-01 00:31:18

回答

4

的标准方法是使用std::sort

#include <algorithm> 

// ... 

std::sort(sname, sname + StudentNum); 

std::sort使用operator<默认情况下,这实际上确实为字符串按字母顺序进行比较。

编辑:事实上,它应该是StudentNum代替25.

+2

应该是'sname + StudentNum' – qwertymk 2011-04-01 00:19:48

+0

我这样做,出现在输出中。 – 2011-04-01 00:21:07