c++ - 在 C++ 中对对象数组进行排序
问题描述
我是新手,这是我的第一个问题。所以我正在为一个任务组织者工作,我想按任务的“紧迫性”值来组织任务列表。这是我的代码:
#include <iostream>
#include <math.h>
#include <vector>
#include <stdlib.h>
#include <list>
using namespace std;
struct Task {
public:
string name;
float deadline, estimated;
int urgency;
int getUrgency() {
urgency = ceil(deadline - estimated);
return urgency;
}
};
void newTask(Task task[], int n1) {
for (int i = 0; i < n1; i++)
{
system("cls");
cout << "Input task name: ";
cin >> task[i].name;
cout << "Input task deadline (in hours): ";
cin >> task[i].deadline;
cout << "Input task estimated work time (in hours): ";
cin >> task[i].estimated;
}
}
void printAll(Task task[], int n1) {
system("cls");
cout << "Name\tDeadline\tEstimated\tUrgency\n";
for (int i = 0; i < n1; i++)
{
cout << task[i].name << "\t" << task[i].deadline << "\t\t" << task[i].estimated << "\t\t" << task[i].getUrgency() << endl;
}
}
int main() {
int n;
cout << "How many work do you have? ";
cin >> n;
//Create number of object based on input n
std::vector<Task> p(n);
newTask(p.data(), n);
std::list<Task> taskList;
printAll(p.data(), n);
cin.ignore();
return 0;
}
我想添加一个按“紧急”值对任务列表进行排序的函数。我应该使用什么样的功能?
解决方案
在您的情况下,您可以在定义自定义比较函数的向量上使用std::sort
标题中定义的函数<algorithm>
:p
std::sort (p.begin(), p.end(), sortTaskByUrgency);
其中sortTaskByUrgency()
定义为:
bool sortTaskByUrgency(const Task& lhs, const Task& rhs)
{
return lhs.getUrgency() < rhs.getUrgency();
}
在示例代码中使用上述函数getUrgency()
必须是const
:
int getUrgency() const { return ceil(deadline - estimated); }
删除无用int urgency
的公共成员。
推荐阅读
- mongodb - MacOS Homebrew 的 MongoDB 社区问题
- python - 如何对涉及两个数据帧的条件的熊猫行迭代进行矢量化?
- generics - 将具有泛型类型参数的结构转换为特定类型
- ajax - tabView: event.getTab() 在 Mojarra 2.3 中总是为空 - 替代方案?
- web-scraping - 为什么每当从网站上抓取信息时都会出现此错误?
- python - 尝试从邮递员发帖时收到一条错误消息,指出“没有名为收容所的列”
- javascript - 如何在 map 函数中累积值并存储在 useState 中
- linux - 将 Windows .exe 文件转换为二进制内容
- docker - Docker:除了 docker-compose.yml 之外,如何使用 Dockerfile
- google-analytics - Google Ads 报告中未显示 GA 数据