如何对类数组进行排序
How to sort a class array
我正在尝试对一个包含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());
}
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 合并排序不排序自创建数组类 c++
- 带有枚举方向/类型的气泡排序结构数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序并行数组
- 如何在数组 c++ 中对字符串进行排序
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何对不在数组中的变量进行排序?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 按字母顺序对结构内数组变量中的名称进行排序
- 使用排序函数 c++ 对字符数组进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 对 0 、1 和 2 的数组进行排序