如何在类中对数组值进行排序

时间:2015-10-13 03:13:12

标签: c++

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

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)

2 个答案:

答案 0 :(得分:1)

你应该比较电影的一年,但要更换整个元素,而不仅仅是它们的标题,如下:

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

答案 1 :(得分:1)

对数组进行排序的更有效或更清晰的方法可能是添加运算符&lt;到结构然后用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);