通过算法头文件中定义的 sort() 函数对 c++ 中的元素对结构数组进行排序
Sort structure array on basis of an element in c++ by sort() function defined in algorithm header file
我有结构:-
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;});
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 从控制台中删除最后打印的元素
- 擦除while循环中迭代的元素