2013-03-08 41 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];