Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;排序向量字符串不工作_C++_String_Vector_Compare - Fatal编程技术网

C++ C++;排序向量字符串不工作

C++ C++;排序向量字符串不工作,c++,string,vector,compare,C++,String,Vector,Compare,由于某种原因,我无法正确地得到这类名称。谁能告诉我它有什么毛病吗?据我所知,问题在于字符串的比较不正确。我以前尝试过字符串比较,我知道这种代码应该可以工作。这真让我难堪 #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; void sortNames(vector<string> &);

由于某种原因,我无法正确地得到这类名称。谁能告诉我它有什么毛病吗?据我所知,问题在于字符串的比较不正确。我以前尝试过字符串比较,我知道这种代码应该可以工作。这真让我难堪

#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;
void sortNames(vector&);
void main()
{
矢量名称列表;
ifstream名称文件;
namesFile.open(“Names.txt”);
//确保该文件存在。
如果(名称文件)
{
//从文件中获取名称。
字符串名;
while(getline(名称文件,名称))
名称列表。推回(名称);
//对导入的名称进行排序。
sortNames(名称列表);
对于(int i=0;icout问题是:这条线

string name = list[i];
应该是

string name = list[lowIndex];

您当前的实现将
j
处的元素与迄今为止找到的最小字符串进行比较,而将其与索引
i
处的字符串进行比较。这是不正确的,因为它没有找到剩余的最小字符串:相反,它会在
向量
中找到小于当前元素i的最后一个字符串ndex
i
,这不是你想要的。

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

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