如何在类中对数组值排序

How to sort array values inside a class

本文关键字:数组 排序      更新时间:2023-10-16

我想按升序对输入进行排序。但它似乎只排序整数…我的排序方法基于冒泡排序。抱歉,如果我的帖子太乱了…我在这里的第一篇文章:

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";
}

的输出
     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)

我希望输出是:

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

你应该比较电影的年份,但要替换整个元素,而不仅仅是它们的标题,像这样:

d = films[n];
films[n] = films[y]; 
films[y]= d;

对数组进行排序的更有效或更简洁的方法可能是添加运算符<到该结构,然后使用std::sort进行排序。这也可以解决你的排序功能的问题。>

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];

用:

替换排序代码
#include <algorithm>
std::sort(films, films + n);