我试图通过对象的1个属性(3个字符串,1个int,1个浮点数)对对象数组进行排序。我需要按照整数排序它们,从最高到最低,然后用字符串按字母顺序排序。我无法理解如何只访问一部分对象。
这是我的所有代码,我已经提供了一些用于排序的示例代码。
#include<iostream>
using namespace std;
#include "video.h"
int main() {
const int MAX = 100;
Video *video[MAX]; //up to 100 videos
for(int l = 0; l < MAX; l++)
{
video[l] = NULL;
// cout << video[l] << endl; //testing if all are equal to 0
}
string title;
string url;
string desc;
string sorting;
float length;
int rate;
// cout << "What sorting method would you like to use?" << endl;
getline(cin, sorting);
//cout << "Enter the title, the URL, a comment, the length, and a rating for each video" << endl;
int t = 0;
while(getline(cin, title))
{
getline(cin, url);
getline(cin, desc);
cin >> length;
cin >> rate;
cin.ignore();
video[t] = new Video(title, url, desc, length, rate);
t++;
}
for(int s = 0; s < t; s++){
video[s]->print();
}
for(int e = 0; e < t; e++)
{
delete video[e];
}
// SORTING
if(sorting == "length") {
int q = 0;
bool Video::longer(Video *video)
{ return m_length > other->m_length; }}
else if(sorting == "rating") {
}
else if(sorting == "title") {
for(int r = 0; r < MAX; r++) {
}
else{
cerr << sorting << " is not a legal sorting method, giving up" << endl;
return 1; }
//this sorts the videos by length
for(int last = num_videos -1; last > 0; last--) {
for(int cur = 0; cur < last, cur++) {
if(videos[cur]->loner(videos[cur+1])) {
swap(videos[cure], videos[cur+1]); }}}
答案 0 :(得分:0)
答案 1 :(得分:0)
如果您想要超出默认值(使用运算符&lt;)的任何排序(排序),您将必须编写自己的比较函数。
我们有一个班级:
class Example
{
public:
std::string thing1;
std::string thing2;
std::string thing3;
int int1;
float f1;
};
std::sort
函数将传递对两个对象的引用。如果第一个参数在第二个参数之前,则比较函数需要返回 true 。
bool comparison(const Example& a, const Example& b)
{
// Compare by their integers.
if (a.int1 < b.int1)
{
return true;
}
if (a.int1 > b.int1)
{
return false;
}
// We can assume the integers are equal.
// Now to compare by strings.
if (a.thing1 != b.thing1)
{
return a.thing1 < b.thing1;
}
// The first strings are equal at this point.
// Compare the second versus the second.
// Which is left as an exercise for the reader.
return false;
}
如果这些对象有std::vector
,请使用std::sort
函数:
std::vector<Example> many_examples;
std::sort(many_examples.begin(), many_examples.end(), comparison);