【问题标题】:Sorting array of objects in c++在 C++ 中对对象数组进行排序
【发布时间】:2021-11-18 01:14:10
【问题描述】:

我是新手,这是我的第一个问题。所以我正在为一个任务组织者工作,我想按任务的“紧迫性”值来组织任务列表。这是我的代码:

#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;
}

我想添加一个按任务“紧急”值对任务列表进行排序的函数。我应该使用什么样的功能?

【问题讨论】:

标签: c++ arrays sorting


【解决方案1】:

在您的情况下,您可以在定义自定义比较函数的p 向量上使用&lt;algorithm&gt; 标头中定义的std::sort 函数:

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公共成员。

【讨论】:

  • 代码给了我这个错误:the object has type qualifiers that are not compatible with the member function "Task::getUrgency" 在 lhs.getUrgency() 和 rhs.getUrgency() 下有红线。
  • 请重新定义 getUrgency() 函数使其成为const: int getUrgency() const { return ceil(deadline - estimated); }
  • @athanasia 我根据您的注释编辑了答案。
【解决方案2】:

我会尝试使用std::sort。它将对任何可迭代对象(数组、向量等)进行就地排序。一个常见的std::sort 函数调用具有以下参数:第一个参数是一个迭代器/指向集合开头的指针,第二个参数是一个迭代器/指向同一集合末尾的指针,第三个参数是一个函数确定数据如何排序的回调。你可以看到一个示例实现here

【讨论】:

  • 您不需要将数据复制到std::vectorstd::sort 算法也适用于数组。指针用作随机访问迭代器。
  • @Blastfurnace 我没有意识到这一点。我会更新我的答案,谢谢! :)
  • 战术说明:Stack Overflow 用户倾向于对指向 cplusplus.com 的链接皱眉,因为 cplusplus 倾向于易于阅读,而不是材料的准确性。 cppreference's documentation 通常更精确,但代价是看起来像是从火星翻译过来的。如果 cplusplus 的建议似乎不起作用,请切换到 cppreference。从长远来看,您会发现自己使用 cpprefference 的频率更高,因为正确几乎总是胜过简单。
  • @user4581301 感谢您的建议。当我想详细了解某个主题时,我会使用 cppreference。虽然 cplusplus.com 的大部分文档都不是最新的,而且它并不严谨,但我认为 std::sort 的示例代码有助于收集基本的理解。
猜你喜欢
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
相关资源
最近更新 更多