【问题标题】:Sort structs by char array (name) (c++) [duplicate]按字符数组(名称)(c ++)对结构进行排序
【发布时间】:2023-03-11 01:44:01
【问题描述】:

我有一个如下所示的结构:

struct employee
{
    char name[21], surname[21];
    unsigned int salary;

}employees[20];

我的问题是,如何按字段“名称”对结构数组进行排序,按字母顺序排序。

我见过人们使用sort()qsort(),但我不知道如何制作您通常必须为这些排序算法制作的compare()

【问题讨论】:

    标签: c++ sorting struct char qsort


    【解决方案1】:

    只需使用 lambda 表达式作为示例

    #include <iterator>
    #include <algorithm>
    #include <cstring>
    
    //...
    
    std::sort( std::begin( employees ), std::end( employees ),
               []( const auto &em1, const auto &em2 )
               {
                   return strcmp( em1.name, em2.name ) < 0;
               } );
    

    在结构中使用std::string类型的对象要好得多。

    【讨论】:

    • 另一种方法是使用有序地图
    • 这是正确的。理想情况下,name 将是 std::string,以避免需要 strcmp
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2016-05-21
    相关资源
    最近更新 更多