2011-04-01 264 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