Search code examples
c++operator-overloadingselection-sort

How can I make a selectionSort in C++ function involving a class, and with an overload of operation < for an array?


I do not know how to how to call my operator< function into my selectionSort function. The selectionSort function is supposed to arrange the blog objects in the array from newest to oldest. The operator< function is comparing the days elapsed since the blog post of each blog. I could use some help on how to set up my selectionSort function which calls the operator< function.

Errors include: -In function 'void selectionSort(Blog*, int)': -[Error] 'class Blog' has no member named 'operator<' -[Error] 'displayData' was not declared in this scope

void selectionSort(Blog blog[], int numBlogs)
{
    Blog temp;
    int minIndex=0;
    for (int i=0; i<numBlogs-1; i++)
    {
        minIndex = i;
        for (int j=i+1; j<numBlogs; j++)
        if (blog[j].operator<())
            minIndex=j;
                        //swap positions i and minIndex
        temp = blog[i];
        blog[i] = blog[minIndex];
        blog[minIndex] = temp;
        displayData(blog, numBlogs);
        
        
    }
}

    bool Blog::operator< (const Blog &right) const
        {
            if (daysElapsed() < right.daysElapsed())//comparing two objects that are in the blog[]
                return true;
           else
               return false;
        }

Solution

  • The whole point of overloading an operator is so that you don't have to spell it out like a function call.

    So for this line:

    if (blog[j].operator<())
    

    apart from the fact that you're missing the argument to operator<, you can just compare 2 Blog objects like this:

    if (blog[j] < blog[i])
    

    If you explicitly want to spell out the operator call, you could do:

    if (blog[j].operator<(blog[i]))