对对象数组C++的故障排序
我试图按对象属性中的1个对对象数组进行排序,3个字符串,1个int,1个float。我需要按整数从高到低排序,然后按字符串按字母顺序排序。我无法理解如何仅访问对象的一部分 这是我所有的代码,我已经包含了一些用于排序的示例代码对对象数组C++的故障排序,c++,arrays,sorting,object,C++,Arrays,Sorting,Object,我试图按对象属性中的1个对对象数组进行排序,3个字符串,1个int,1个float。我需要按整数从高到低排序,然后按字符串按字母顺序排序。我无法理解如何仅访问对象的一部分 这是我所有的代码,我已经包含了一些用于排序的示例代码 #include<iostream> using namespace std; #include "video.h" int main() { const int MAX = 100; Video *video[MAX]; //up to 100
#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]); }}}
您可以看看std::sort
您可以创建一个自定义比较器来比较您希望比较的对象部分。如果您希望使用默认运算符进行任何排序,则有许多类似的现有问题和答案-例如。如果你试图遵循这种方法而陷入困境,请展示你的代码并记录你遇到的具体问题。我已经阅读了许多关于这一点的帖子,但没有一篇文章以对我有意义的方式解释了实际过程,并且可以应用于我的特定程序。如果你能展示你所做的一切,那就太好了,只需添加您当前的代码,我们就可以帮助您了解让StackOverflow用户了解哪些内容对您有意义,哪些内容可以应用于您的特定程序是错误的,我建议您提供足够的信息。例如,显示您的代码并突出显示缺失的部分。这是您今天就代码提出的第三个问题。
class Example
{
public:
std::string thing1;
std::string thing2;
std::string thing3;
int int1;
float f1;
};
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<Example> many_examples;
std::sort(many_examples.begin(), many_examples.end(), comparison);