C ++排序矢量字符串不起作用

时间:2013-03-08 22:49:00

标签: c++ string vector compare

出于某种原因,我无法正确地获得这种名称。谁能告诉我它有什么问题?据我所知,问题是字符串没有正确比较。我以前尝试过字符串比较,我知道这种代码应该可行。真的让我难过。

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

2 个答案:

答案 0 :(得分:5)

问题在于:这一行

string name = list[i];

应该是

string name = list[lowIndex];

您当前的实现将j处的元素与您到目前为止找到的最小字符串进行比较,而不是将其与索引i处的字符串进行比较。这是不正确的,因为它找不到最小的剩余字符串:相反,它找到vector中的最后一个字符串,该字符串小于索引i处的当前元素,这不是您想要的。

答案 1 :(得分:0)

而非string name = list[i];,您需要string name = list[lowIndex];