2014-02-09 177 views
0

我有一個作業問題我遇到了一些問題,我被要求使用C++按字母順序排列C字符串數組,排序算法必須是冒泡排序。我迄今爲止所做的(在下面複製)可以對數組進行排序,但僅基於第一個字母表。我如何進一步用相同的首字母表對字符串進行排序?按字母順序排列c字符串數組

<snipped>@arch:~/College/OOP/Lab/W3$ cat 2.cpp 

/* 
* Write a function which sorts an array of C strings in ascending order using bubble sort. The 
* number of strings in the array and the array must be passed as parameters to the function 
*/ 

#include <iostream> 
#include <cstring> 

using namespace std; 

void sort(char **sar, unsigned num, unsigned len) 
{ 
    char *temp = new char[len]; 

    if (temp == NULL) 
    { 
     cout << "\nOut-Of-Memory\n"; 
     return; 
    } 

    for (unsigned a = 0; a < num-1; a++) 
    { 
     for (unsigned b = 0; b < ((num-a)-1); b++) 
     { 
      if (sar[b][0] > sar[b+1][0]) 
      { 
       strcpy(temp, sar[b]); 
       strcpy(sar[b], sar[b+1]); 
       strcpy(sar[b+1], temp); 
      } 
     } 
    } 

    delete[] temp; 
} 

int main(int argc, char *argv[]) 
{ 
    char **sar; 
    unsigned num; 
    unsigned len; 

    cout << "Number of Strings: "; 
    cin >> num; 
    cout << "Length of Strings: "; 
    cin >> len; 

    cin.ignore(); // Flush buffer to fix a bug (getline after cin). 

    sar = (char **) new char*[num]; 
    if (sar == NULL) 
    { 
     cout << "\nOut-Of-Memory\n"; 
     return -1; 
    } 

    for (unsigned i = 0; i < num; i++) 
    { 
     sar[i] = (char *) new char[len]; 
     if (sar[i] == NULL) 
     { 
      // Let's pretend we 'know' memory management 
      // because obviously modern OSs are incapable 
      // of reclaiming heap from a quitting process.. 
      for (unsigned j = 0; j < i; j++) 
       delete[] sar[j]; 
      cout << "\nOut-Of-Memory\n"; 
      return -1; 
     } 
    } 

    for (unsigned x = 0; x < num; x++) 
     cin.getline(&sar[x][0], 512); 

    sort(sar, num, len); 

    cout << '\n'; 
    for (unsigned y = 0; y < num; y++) 
     cout << sar[y] << '\n'; 

    for (unsigned z = 0; z < num; z++) 
     delete[] sar[z]; 
    delete[] sar; 

    return 0; 
} 
+0

無效使用delete'的'。你應該使用'delete []'。 – Brandon

+0

究竟在哪裏? valgrind不會像任何事情那樣咧嘴。 – sgupta

+0

也在你的排序功能中。臨近結束時,你可以在臨時調用'delete',它應該是'delete []'。 – Brandon

回答

1

變化

if (sar[b][0] > sar[b+1][0])

if (stricmp(sar[b], sar[b+1]) > 0)

UPDATE:不是stricmp,您可以使用strcasecmp

+0

[That](http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/rzan5mst264.htm)不符合標準, 是嗎? (另請參閱[這裏](http://msdn.microsoft.com/en-us/library/ms235365.aspx)) –

+0

非常感謝!我搜索了一下這個函數,並在g ++手冊中找到了一個相當於strcasecmp的函數。 – sgupta