我将如何对这个数组进行排序
How would I sort this array?
我有一个基于此视频类的数组:
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);
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为