【问题标题】:C++ - sort array by DateC++ - 按日期排序数组
【发布时间】:2021-01-09 19:05:40
【问题描述】:

我正在学习 C++。我创建了两个结构(日期和电话):

struct Date {
    unsigned int day, month, year;
};

struct Phone {
    std::string name;
    Date purchase_date;
};

然后我用 std::cin 为多部手机插入一些数据。我的主要功能:

int main()
{
    Phone *phone[3];
    phone[0] = new Phone;
    phone[1] = new Phone;
    phone[2] = new Phone;
    
    insertDataForPhone(*phone, 3);

    for(unsigned short itr = 0; itr < 3; itr++)
    {
        delete phone[itr];
    }

    std::cin.get();
    return 0;
}

我的问题是:如何按创建的日期(升序)对数组电话进行排序?

【问题讨论】:

  • 对于排序,您应该使用 STL 的排序功能,除非您想重新发明轮子以进行学习,但是您当前的代码存在很多问题,我怀疑它甚至可以编译...
  • 我可以通过移动指针以某种方式做到这一点吗?
  • 各种库排序函数都接受一个自定义函数,该函数可以获取指针,然后对尖顶对象的成员执行比较。 Sorting Array of Pointers in C++ 足以让您入门吗?
  • 请看我的回答,我相信你会发现比运算符重载更容易理解,因为你正在学习C++。如果您还有其他问题,请随时提问。
  • @LukeG,看看这个链接,例如:geeksforgeeks.org/sort-c-stl

标签: c++ pointers struct


【解决方案1】:

您可以将std::sort 与自定义比较器一起使用。比较器用于判断第一个参数是否“小于”第二个参数:

#include <algorithm>  // std::sort
#include <string>     // std::string, std::begin, std::end

struct Date {
  unsigned int day, month, year;
};

// Compare dates
bool operator<(Date const& lhs, Date const& rhs) noexcept {
  if (lhs.year < rhs.year) return true;
  if (lhs.year > rhs.year) return false;

  if (lhs.month < rhs.month) return true;
  if (lhs.month > rhs.month) return false;

  return lhs.day < rhs.day;
}

struct Phone {
  std::string name;
  Date purchase_date;
};

// Comparator for sorting
bool purchased_earlier(Phone const* p1, Phone const* p2) noexcept {
  return p1->purchase_date < p2->purchase_date;
}

int main() {
  Phone* phone[3];
  // ...
  std::sort(std::begin(phone), std::end(phone), purchased_earlier);
}

对于Date 类,只比较它们是有意义的。所以,我重载了operator&lt;。在Phone 的情况下,比较手机没有多大意义,而且我们是根据购买日期进行比较也不是很明显,所以我创建了一个命名函数,并将其传递给std::sort

【讨论】:

  • 谢谢。这正是我想要的。
【解决方案2】:

或者,您可以按购买日期映射这些手机,并且感谢std::map,它会自动排序。如果您正在学习 C++,这会简单得多,您将学会使用 tm 结构。

#include <iostream>
#include <string>
#include <ctime>
#include <map>
struct Phone{
    std::string name;
    tm purchase_date;
};
std::map<time_t,Phone*> Phones;
int main()
{
    Phone* phone1=new Phone{"phone1",{0,0,0,9,0,121}}; //01.09.21
    Phone* phone2=new Phone{"phone2",{0,0,0,30,11,120}}; //12.30.20
    Phones[mktime(&phone1->purchase_date)]=phone1;
    Phones[mktime(&phone2->purchase_date)]=phone2;
    for(auto it=Phones.begin(); it!=Phones.end(); it++)
        std::cout<<it->second->name<<std::endl;
}

输出:

phone2
phone1

因为 phone2 是较早购买的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多