2

何らかの理由で、このソート名を正しく取得できません。誰がそれの何が悪いのか教えてもらえますか? 私が知る限り、問題は文字列が正しく比較されていないことです。以前に文字列比較を試したことがありますが、この種のコードが機能することはわかっています。それは本当に私を困惑させました。

#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;
        }
    }
}
4

2 に答える 2

5

ここに問題があります: この行

string name = list[i];

する必要があります

string name = list[lowIndex];

現在の実装では、要素をjこれまでに見つかった最小の文字列ではなく、 index の文字列と比較しますi。残りの最小の文字列を見つけられないため、これは正しくありません。代わりに、vectorindex の現在の要素よりも小さい最後の文字列を見つけiます。これは、必要なものではありません。

于 2013-03-08T22:53:03.547 に答える
0

ではなくstring name = list[i];、あなたが欲しいstring name = list[lowIndex];

于 2013-03-08T22:54:02.453 に答える