【问题标题】:How do I sort a structure that contains say employee details by name [duplicate]如何按名称对包含员工详细信息的结构进行排序[重复]
【发布时间】:2021-02-23 00:25:14
【问题描述】:

所以我有一个包含以下内容的结构,

stuct details {
int emp_id;
int age;
char name[50];
};

所以这个结构的数据已经存在于一个二进制文件中并且我已经读取了该文件,现在我如何继续按名称对其进行排序? 可以使用 std::sort 吗?我将如何为其编写函数?

【问题讨论】:

  • std::sort 使用比较功能sort( RandomIt first, RandomIt last, Compare comp ); 非常适合您的工作。
  • RandomIt first 和 RandomIt last 包含什么?
  • 它们包含std::sort 的文档中所说的内容。您是否已经阅读了std::sort 的免费文档,如果没有阅读,为什么不阅读?如果您这样做并且您不理解文档中的某些内容,那么您到底不清楚什么?
  • 我确实读过它们。我知道它是排序(startaddress,endaddress,comparator),但由于我的输入是一个名字说“abc def”,开始和结束将如何工作?如果它只是一个 int 数组,我得到的格式是 n = sizeof(arr)/sizeof(arr[0]);但是空间的出现呢?
  • @Ashwar 查看我刚刚发布的答案。

标签: c++ sorting struct


【解决方案1】:

如果我正确理解您的问题,您必须重载比较运算符 (),然后添加代码来比较字符数组。我建议使用 stdlib 中的 std::string 而不是构建自己的比较函数,除非您需要 name 成员是 char 数组。这应该可以帮助您开始:

struct details {
    int emp_id;
    int age;
    char name[50];
    bool operator<(const details a) {
        //You'll have to find the code to compare character arrays. But that will be a quick google search.
    }
};

这将允许您决定使用的任何容器的排序功能以正确的顺序放置它们。

【讨论】:

    【解决方案2】:

    您不会对结构的单个实例进行排序。您对结构容器进行排序。是数组还是向量等,由你决定。

    您将读取文件,根据需要使用您的结构实例填充容器,然后您将传递 begin/end iterators 以获得要排序的容器元素范围,提供一个根据需要比较结构的 2 个给定实例的字段的比较器。

    例如:

    struct details {
        int emp_id;
        int age;
        char name[50]; // why not std::string?
    };
    
    std::vector<details> employees;
    // populate employees as needed...
    
    std::sort(employees.begin(), employees.end(),
        [](const details &emp1, const details &emp2){
            return std::strncmp(emp1.name, emp2.name, 50) < 0;
        }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多