0

I wanted to sort the inputs by ascending order. but it seems to be sorting the integers only.. I based the sorting method on Bubble Sort.. Sorry if my post is too messy.. My first post here :(

using namespace std;

struct movies_t{

    string title;
    int year;
}films[3];

void printmovie (movies_t movie);

int main ()
{
    string mystr;
    int n,t;
    string d;

    for(n=0;n<3;n++)
    {

        cout <<"Enter title:";
        getline(cin,films[n].title);
        cout <<"Enter year:";
        getline(cin,mystr);
        stringstream (mystr)>> films[n].year;

    }

    for(n=0;n<3;n++)
    {
        for(int y=0; y<3; y++)
        {
            if(films[n].year < films[y].year)
            {
                t = films[n].year;
                films[n].year = films[y].year;
                films[y].year = t;
            }

            if(films[n].title < films[y].title)
            {
                d = films[n].title;
                films[n].title = films[y].title;
                films[y].title = d;
            }
        }
    }

    cout <<"\n You have entered these movies:\n";
    for(n=0;n<3;n++)
        printmovie (films[n]);
    return (0);
}

void printmovie(movies_t movie)
{
    cout <<movie.title;
    cout <<"("<<movie.year<<")\n";
}

The Ouput

     Enter title:a
     Enter year:2001
     Enter title:d
     Enter year:2011
     Enter title:f
     Enter year:2005

     You have entered these movies:
     a(2001)
     d(2005)
     f(2011)

I wanted the output to be:

     You have entered these movies:
     a(2001)
     f(2005)
     d(2011)

2 Answers 2

1

you should compare film's year, but replace the whole elements, not only their titles, like this:

d = films[n];
films[n] = films[y]; 
films[y]= d;
Sign up to request clarification or add additional context in comments.

1 Comment

this answer breaks the relationship between title and year
1

A more efficient or cleaner way to sort your array could be to add the operator < to the structure and then sort with std::sort. that'd also solve your problem with your sorting function.

struct movies_t{

    string title;
    int year;

    bool operator<(const movies_t& rhs) const
    {
        if (year < rhs.year)
            return true;
        if (year > rhs.year)
            return false;
        return title < rhs.title;
    }

}films[3];

replace sorting code with:

#include <algorithm>

std::sort(films, films + n);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.