如何对类数组进行排序

How to sort a class array

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

我正在尝试对一个包含5个值的类数组进行排序。3个字符串和2个int。我想根据int值从高到低对数组进行排序,但不知道如何做到这一点。我的through过程是将数组发送到类中,然后提取正确的int值,并对每个数组位置进行排序,而不更改该位置的其他值。如何提取这些值,以便对其进行相应的排序?如果可以的话,我就会知道如何完成我的代码。如果有更简单的方法可以做到这一点,那么我愿意接受任何建议。

在下面的代码中,我有一个模板,如果我能提取出这个数字,我会怎么做:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Thing
{
public:
  Thing();
  void setvariables(string s, string g, string a, int y, int l);
  void get();
  void print();
  void sort_time(Thing data[], int datasize);
private:
  string name;
  string genre;
  string artist;
  int year;
  int length;
};
Thing::Thing()
{
  name = "";
  genre = "";
  artist = "";
  year = 13;
  length = 15;
}
void Thing::setvariables(string n, string g, string a, int y, int l)
{
  name = n;
  genre = g;
  artist = a;
  year = y;
  length = l;
}
/* void Thing::sort_time(Thing data[], int datasize)
{
int lar_pos, pos, lar_val;
for (int index = 0; index < datasize; index++)
{
    lar_pos = index;
    lar_val = data[index].get();
    for (pos = index; pos < datasize; pos++)
    {
        if (data[pos] > data[lar_pos])
        {
            lar_pos = pos;
            lar_val = data[lar_pos];
        }
    }
    data[lar_pos] = data[index];
    data[index] = lar_val;
}
}
void Thing::get()
{
l = length;
}
*/
void Thing ::print()
{
    cout << setw(25) << name << setw(10) << genre << setw(5) << year
    << setw(30) << artist << setw(5) << length << endl;
}
int main()
{
  // Create array of things
  int size = 9;
  Thing array[9];
  // Initialize array of things
  for (int i = 0; i<size; i++)
  {
    string name, genre, artist, junk;
    int year, length;
    getline(cin, name);
    getline(cin, genre);
    getline(cin, artist);
    cin >> year;
    cin >> length;
    array[i].setvariables(name, genre, artist, year, length);
    cin.ignore(256, 'n');
  }
  // Print array of things
  cout << setw(25) << "TITLE" << setw(10) << "GENRE" << setw(5) << "YEAR"
     << setw(30) << "ARTIST" << setw(5) << "TIME" << endl;
  cout << setw(25) << "=====" << setw(10) << "=====" << setw(5) << "===="
     << setw(30) << "======" << setw(5) << "====" << endl;
  for (int i = 0; i<size; i++)
    array[i].print();
  return 0;
}

std::sort与自定义比较器一起使用,或为您的类型定义operator<

示例:

#include <algorithm>
class Thing
{
  // ...
};
class ThingComparator
{
  bool operator()(const Thing& a, const Thing& b)
  {
    // Define your logic here and return true if a is considered lesser than b.
  }
};
int main()
{
  const int size = 9; // Make it constant!!
  Thing array[size];
  // Fill the array ...
  // Then sort it
  std::sort(array, array + size, ThingComparator()); 
}