2016-11-29 35 views
0

我是C++的新手,我必須使字符串按照使用bubblesort的升序顯示。我有一個數據文件,其中包含各種字符串。我將這些值存儲到一個數組中。當我嘗試從我的教科書中的bubblesort代碼時,這些單詞就像這樣排序。如何用C++中的字符串做bubblesort?

我該如何正確實施?這可能很簡單,我錯過了。謝謝。

enter image description here

我不知道爲什麼會這樣,但這裏是我使用的冒泡排序的代碼。

void sortListWords(string list[], int count) { 
    int temp; 
    for (int i = 0; i < count - 1; i++) 
    for (int j = 0; j < count - (i + 1); j++) 
     if (list[j] > list[j + 1]) { 
     temp = list[j]; 
     list[j] = list[j + 1]; 
     list[j + 1] = temp; 
     } 
    } 

int main(){ 
    // call sorting function 
    // words are loaded from data file 
    sortListWords(wordListing, size); 

    // print array to screen 
    for(int i=0; i<size; i++) 
    cout << wordListing[i]; 

    return 0; 
} 
+1

你想他們按字典順序排序?同時請澄清你在哪裏定義'尺寸'。 –

+3

我不明白這是如何編譯的,因爲你使用'int'臨時變量交換'std :: string'值。 –

+0

它實際上與泡泡類整數相同。你可以寫代碼來冒泡排序一個整數數組嗎?如果是這樣,唯一的區別將是使用的類型 - 其他所有內容保持不變。 – PaulMcKenzie

回答

1

只對您的示例做了最小的更改。請你所擁有的比較吧,你會看到,你的問題是:

#include <string> 
#include <iostream> 

void sortListWords(std::string list[], int count) { 
    std::string temp; 
    for (int i = 0; i < count - 1; i++) { 
    for (int j = 0; j < count - (i + 1); j++) { 
     if (list[j] > list[j + 1]) { 
     temp = list[j]; 
     list[j] = list[j + 1]; 
     list[j + 1] = temp; 
     } 
    } 
    } 
} 

int main(){ 
    const int size = 4; 
    std::string wordListing[] = {"Hello", "World", "Fred", "John" };  

    // call sorting function 
    // words are loaded from data file 
    sortListWords(wordListing, size); 

    // print array to screen 
    for(int i=0; i<size; i++) { 
    std::cout << wordListing[i] << '\n'; 
    } 
    return 0; 
} 

我特別做了什麼,從int交換的temp類型std::string。我還在您的for循環的身體周圍添加了大括號,以提高可讀性。

最後我添加的第一個兩行(用於測試)您main功能:

const int size = 4; 
    std::string wordListing[] = {"Hello", "World", "Fred", "John" }; 

輸出是:

Fred 
Hello 
John 
World 
0

更改此int temp;string temp;

+0

你真的應該使用std :: string – CodeLikeBeaker

+0

我假設提交者正在使用std命名空間。謝謝 –