Reputation: 3
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)
Upvotes: 0
Views: 101
Reputation: 896
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);
Upvotes: 1
Reputation: 422
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;
Upvotes: 1