Search code examples
c++arrayssortingstructure

Sorting names in an array variable inside a structure alphabetically


I'm making this student record program that my prof asked us to do. It keeps saying cannot convert 'StudRec' to 'StudRec' in assignment and sometimes it says cannot convert char* to const char*. StudRec is my struct variable and this is the function that should sort the recorded names alphabetically.

void sort_name(StudRec name[], StudRec temp[], int studcount)
{
    if (studcount > 0)
    {
        for (int i=0; i<studcount; i++)
        {
           for (int j=studcount; j<=i; j++)
            {
                if(strcmp(name[j].nm, name[j+1].nm) > 0)
                {
                        temp=name[j];
                        name[j]= name[j+1];
                        name[j+1]= temp;
                }
            }
        }
        cout << "\t| |\t\t\t The records have been sorted alphabetically by name.\n";
    }

    else
    {
        cout << "\t| |\t\t\t There is no current record to sort by name.\n\n";
    }
}

Solution

  • Ok, assuming that the StudRec has all necessary operations (assignment, default constructor, etc.), you don't need to pass an array of temp values:

    void sort_name(StudRec name[], int studcount)
    {
        StudRec temp;
        // ...
    }
    

    That should fix one issue: you are trying to assign an element to the whole array:

            temp=name[j];
    

    Even better would be to define temp right where you use it:

            const StudRec temp = name[j];
    

    Anyway, I guess you are trying to implement a BubbleSort, and your implementation is incorrect because of the indexing. Should be:

        for (int i = 1; i < studcount; ++i)
            for (int j = 0; j < studcount - i; ++j)