Search code examples
c++arrayssortingstructtolower

Trouble bubble sorting alphabetically in struct array


When trying to bubble sort an inventory stored in a struct array, I am getting two different errors when I compile the code below:

void SORT_INVENTORY(Books* list, int max, int position)
{
        bool swap;
        string temp;

        do
        {
                swap = false;
                for (int count = 0 ; count < (position - 1) ; count++)
                {
                        if ( tolower(list[count].Title) > tolower(list[count + 1].Title)) 
                        {
                                temp = list[count];
                                list[count] = list[count + 1];
                                list[count + 1] = temp;
                                swap = true;
                        }
                }
        } while (swap);

I wish to use tolower to compare the Title element of two struct arrays. However, compiler won't let me run the program because it says that no matching function to call for tolower.

When I switch the if statement to this:

if ( ::tolower(list[count].Title) > ::tolower(list[count + 1].Title)) 

The "no matching function" message goes away but is replaced by a new one: no viable conversion from 'string' (aka 'basic_string, allocator >') to 'int'.

Lastly I get a consistent error message regarding statments in the body of the if statement, stating no viable overloaded '=' in temp = list[count] and list[count + 1] = temp.

One last detail: list is an array declared as a struct data type. What am I doing wrong?


Solution

    1. tolower works on a single character, not a string. Check out How to convert std::string to lower case?
    2. You are trying to assign a Book to a string (and vice versa). Change the type of temp.