c++ - 如何在 C++ 中按字母顺序排列数组中的字符串?

标签 c++ sorting

我必须编写一个程序,将 10 个人按高度排序,然后按姓氏排序。我已经降低了高度,但我无法对姓氏进行排序。我正在尝试为此使用 strcmp。每当我尝试运行它时,它都会在 strcmp 上标记一个错误,说,"[Error] cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1 ' to 'int strcmp(const char*, const char*)'" 我使用 strcmp 是因为这是一项学校作业,我受限于我对 c++ 的了解以及我的教授允许我们使用的内容

int main()
{
    const int SIZE = 10;
    int count = 0;
    bool flag = true;
    string fileName;
    ifstream inputFile;
    string firstName[SIZE];
    string lastName[SIZE];
    int height[SIZE];

    cin >> fileName;
    inputFile.open(fileName.c_str());

    while(count < 10)
    {
        inputFile >> firstName[count];
        inputFile >> lastName[count];
        inputFile >> height[count];
        count++;
    }
    //Sort based on height
    for(int max = SIZE - 1; max > 0 && flag; max--)
    {
        flag = false;

        for(int line = 0; line < max; line++)
        {
            if(height[line] > height[line + 1])
            {
                swap(height[line], height[line + 1]);
                swap(firstName[line], firstName[line + 1]);
                swap(lastName[line], lastName[line + 1]);
                flag = true;
            }
        }
    }
    //Sort based on last name if heights are equal
    for(int max = SIZE - 1; max > 0 && flag; max--)
    {
        flag = false;

        for(int line = 0; line < max; line++)
        {
            if(height[line] == height[line + 1])
            {
                if(strcmp(lastName[line], lastName[line + 1]) > 0)
                {
                    swap(height[line], height[line + 1]);
                    swap(firstName[line], firstName[line + 1]);
                    swap(lastName[line], lastName[line + 1]);
                    flag = true;
                }
            }
        }
    }

最佳答案

如果您坚持使用旧的strcmp 函数,那么您应该传递lastName[line].c_str() lastName[line+1].c_str() 作为其参数。但是,您最好使用 STL 提供的 std::string::compare() 函数:

if (lastName[line].compare(lastName[line + 1]) > 0)

这做同样的事情。

或者更简单(如 Fred Larson 所建议的):

if (lastName[line] > lastName[line+1])

关于c++ - 如何在 C++ 中按字母顺序排列数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59036335/

相关文章:

c++ - 无法打开包含文件 : 'ntddk.h' : No such file or directory

python - 在一行中打印 for 循环结果并排序

r - dplyr::summarize_at – 按传递的变量顺序对列排序,然后按应用函数的顺序排序

Java - 如何在for循环中修改数组并在for循环退出后记住它?

bash - 帮助使用 sort 对文件进行排序

c++ - 无法在 Socket 编程中将 int 从服务器发送到客户端

c++ - 在 return 语句中取消引用的指针会发生什么?

c++ - 为什么我需要使用动态内存分配,而我可以从静态中实现相同的目的?

C++ 逻辑恒常性和从 const 方法按值返回

python - Python 中的冒泡排序排序不正确