2013-03-08 40 views
2

由於某種原因,我無法正確地得到這種排序的名稱。誰能告訴我它有什麼問題?據我可以告訴問題是字符串不能正確比較。我曾嘗試過字符串比較,而且我知道這種代碼應該可以工作。它真的讓我難住。C++排序矢量字符串不工作

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 

using namespace std; 

void sortNames(vector<string> &); 

void main() 
{ 
    vector<string> namesList; 
    ifstream namesFile; 
    namesFile.open("Names.txt"); 

    // Make sure the file exists. 
    if (namesFile) 
    { 
     // Get the names from the file. 
     string name; 
     while (getline(namesFile, name)) 
      namesList.push_back(name); 

     // Sort the imported names. 
     sortNames(namesList); 

     for (int i = 0; i < namesList.size(); i++) 
      cout << namesList[i] << endl; 
    } 
    else 
    { 
     cout << "Data files are missing"; 
    } 

    namesFile.close(); 
} 

void sortNames(vector<string> &list) 
{ 
    for (int i = 0; i < list.size(); i++) 
    { 
     // Find the lowest value after i. 
     int lowIndex = i; 
     for (int j = i + 1; j < list.size(); j++) 
     { 
      string name = list[i]; 
      string name2 = list[j]; 

      if (name > name2) 
       lowIndex = j; 
     } 

     // Flip the elements if there was a value lower than i. 
     if (i != lowIndex) 
     { 
      string temp = list[i]; 
      list[i] = list[lowIndex]; 
      list[lowIndex] = temp; 
     } 
    } 
} 
+7

你知道你可以使用'的std :: sort'排序向量? – 2013-03-08 22:51:03

+2

這是一本教科書中的學習練習,用於學習排序和搜索算法。 – Emrys90 2013-03-08 22:54:33

回答

5

這裏的問題是:這行

string name = list[i]; 

應該

string name = list[lowIndex]; 

您目前執行的元素在j比較不是你已經迄今爲止發現的最小的字符串,而是索引爲i的字符串。這是不正確的,因爲它找不到最小的剩餘字符串:相反,它找到vector中的最後一個字符串,它小於索引i處的當前元素,這不是您想要的。

+0

謝謝。我不能相信我錯過了這一點。 – Emrys90 2013-03-08 22:55:52

0

而非string name = list[i];,你想string name = list[lowIndex];