简体   繁体   English

C ++按字母顺序对名称进行排序

[英]c++ sorting names alphabetically

I have a program that is trying to sort some names alphabetically. 我有一个程序试图按字母顺序对一些名称进行排序。 I run it and it does not have any errors, but the names are not sorted. 我运行它,它没有任何错误,但名称未排序。 I compare 2 names and see which one is supposed to be shifted in the array. 我比较了2个名称,看看应该在数组中移动哪个名称。

Here is the code: 这是代码:

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]);
    }
}

My struct looks like this: 我的结构看起来像这样:

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

Do I have to convert these to strings somewhere because they are characters arrays? 我是否必须将它们转换为字符串,因为它们是字符数组? I am kind of lost and trying to figure out how to make it sort properly. 我有点迷茫,试图弄清楚如何使其正确排序。

The Problem is that in this line: 问题是在这一行:

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

it doesn't compare string characters, but rather compares memory adresses. 它不比较字符串字符,而是比较内存地址。

If you still want to use char arrays, you have to use the strcmp function. 如果仍然要使用char数组,则必须使用strcmp函数。 However, I recommed that you use string instead. 但是,我建议您改用string

The problem is this line: 问题是这一行:

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

The line compares the pointers, it does not compare the contents. 该行比较指针,不比较内容。

It should be: 它应该是:

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

Another alternative is to use std::string instead, which has built-in comparisons. 另一种选择是改为使用std :: string,它具有内置的比较功能。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM