c++按字母顺序排序名称

c++ sorting names alphabetically

本文关键字:排序 顺序 c++      更新时间:2023-10-16

我有一个程序,它试图按字母顺序对一些名字进行排序。我运行它,它没有任何错误,但名称没有排序。我比较了两个名字,看看哪一个应该在数组中移位。

代码如下:

void sort_names(char array[])
{
    const int arraysize = 5;
    // Step through each element of the array
    for (int startindex = 0; startindex < arraysize; startindex++)
    {
        int smallestnum = startindex;
        for (int currentindex = startindex + 1; currentindex < arraysize; currentindex++)
        {
            // If the current element is smaller than our previously found smallest
            if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))
            // Store the index 
            smallestnum = currentindex;
        }
        // Swap our start element with our smallest element
        swap(student_list[startindex], student_list[smallestnum]);
    }
}

我的结构是这样的:

struct student {
    char fname[30]; 
    char lname[30];
};

我是否必须将这些转换为字符串,因为它们是字符数组?我有点迷路了,想弄清楚如何使它正确排序

问题是在这一行中:

if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))

它不比较字符串字符,而是比较内存地址。

如果您仍然想使用char数组,则必须使用strcmp函数。但是,我建议您使用string

问题出在这一行:

if ((student_list[currentindex].lname) < (student_list[smallestnum].lname))

行比较指针,但不比较内容。

应该是:

if ( strcmp( student_list[currentindex].lname, student_list[smallestnum].lname ) < 0 )

另一种替代方法是使用std::string,它具有内置比较。例如:

struct student {
    std::string fname; 
    std::string lname;
};