【问题标题】:C++ sorting vector strings not workingC ++排序向量字符串不起作用
【发布时间】:2013-03-08 22:49:00
【问题描述】:

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

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

【问题讨论】:

  • 你知道你可以使用std::sort对向量进行排序吗?
  • 这是一本教科书里学习排序和搜索算法的学习练习。

标签: c++ string vector compare


【解决方案1】:

问题出在这里:这一行

string name = list[i];

应该是

string name = list[lowIndex];

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

【讨论】:

    【解决方案2】:

    而不是string name = list[i];,你想要string name = list[lowIndex];

    【讨论】:

      猜你喜欢
      • 2011-10-30
      • 2016-03-04
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多