我将如何对这个数组进行排序

How would I sort this array?

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

我有一个基于此视频类的数组:

Video::Video(string i, string j, string k, double l, int m) 
{
    title = i; 
    link = j; 
    comment = k; 
    length = l; 
    rating = m;
}

每个数组元素看起来都这样:

videolist[i] = new Video(title, link, comment, length, rating);

现在,说用户想按长度对数组进行排序,最长的视频首先进行。我需要根据最长的视频对数组进行泡泡。为此,我需要发挥功能:

bool Video::longer(Video *other) 
{
    if (/*"other" is greater than the current largest video*/) 
    {
        /*"other" is now the current largest video*/
        return false;
    }
    return true;
}

那么,我将如何隔离"其他"视频的长度并将其与当前最长的视频进行比较?谢谢!

通常,我会去做这种事情:

创建视频类的向量。

std::vector< Video > videoArr;

对于排序,您可以使用<algorithm>中存在的std::sort

您需要做的一切都是:

#include <vector>
#include <algorithm>
std::vector< Video > videoArr;
std::sort( videoArr.begin(), videoArr.end(), []( const Video& lhs, const Video& rhs )
{
   return lhs.length > rhs.length;
});

// In C++14
#include <vector>
#include <algorithm>
 std::vector< Video > videoArr;
std::sort( videoArr.begin(), videoArr.end(), []( const auto& lhs, const auto& rhs )
{
   return lhs.length > rhs.length;
});

您也可以实现< operator> operator并实现案件的少于/大于操作员。

与自定义比较器一起使用std::sort

bool cmp(const Video &i, const Video &j)
{
    return i.length > j.length;
}

std::sort(videolist,videolist+number_of_elements,cmp);