通过算法头文件中定义的 sort() 函数对 c++ 中的元素对结构数组进行排序

Sort structure array on basis of an element in c++ by sort() function defined in algorithm header file

本文关键字:元素 c++ 排序 结构 数组 函数 算法 文件 定义 sort      更新时间:2023-10-16

我有结构:-

typedef struct {
int x;
int y;
}point;

我声明了数组:-

point A[100];

我从用户那里获得了 A 的输入。那么我们如何在 x 元素的基础上对数组 A 进行排序。我知道如何通过编写函数来做到这一点。但是如何使用算法中定义的sort()函数来做到这一点C++

您可以将比较函数传递给std::sort

point A[100];
std::sort(A, A+100, 
          [](const point& f, const point& s) -> bool{
              return f.x < s.x;
          });

您可以将比较器函数作为sort的第三个参数传递。

当然包括algorithm

#include<algorithm>

定义比较器功能。它应该比较两个点,并返回true如果第一个应该在排序数组中的第二个点之前(如果第一个点小于第二个点)。<algorithm>中的sort函数将使用此比较器函数来比较您的项目并将它们按正确的顺序排列。您可以在此处了解有关排序算法的更多信息。如果您需要更高级的材料,可以查找"算法简介"。

bool compare(const point& p1, const point& p2) {
    return p1.x < p2.x;
}

使用 sort 并像这样传递数组和函数:

int main () {
    point A[100];
    std::sort(A, A+100, compare);
    return 0;
}

写入比较器:

inline bool ComparePoints(const point & first, const point & second) {
    return first.x < second.x;
}

之后,您可以拨打std::sort()

std::sort(A, A + 100, ComparePoints);

使用 lambdas:

std::sort(std::begin(A),std::end(A),[](point const& l,point const& r){return l.x<r.x;});