gpt4 book ai didi

C++ 结构或数组排序

转载 作者:行者123 更新时间:2023-11-30 02:30:30 25 4
gpt4 key购买 nike

你好,我有结构排序功能,现在我只是想知道是否有更简单的方法:

void Sorting(Sheeps v[],int all){

for(int a =0; a < all; a++){
for(int b = a+1; b < all; b++){
if(v[b].dna_mach_rate > v[a].dna_mach_rate){
v[4].dna_mach_rate = v[a].dna_mach_rate;
v[a].dna_mach_rate = v[b].dna_mach_rate;
v[b].dna_mach_rate = v[4].dna_mach_rate;
}
}
}
v[4].dna_mach_rate = 0;
}

所以这个函数只是通过结构运行并从最大到最小替换值,但是这样做有很多代码,所以我想知道是否有像“php”或“javascript”这样的函数,“ushort” "或类似的或更好的排序数组或结构的方法这就是我在“javascript”中的做法:

arrayname.sort(function(a, b){return b.speed - a.speed}); 

在 php 中几乎相同,所以我想知道是否有类似甚至更好的方法来对 c++ 中的数组或结构进行排序

最佳答案

std::sort(v, v+all, [](Sheeps const& lhs, Sheeps const& rhs){
return lhs.dna_mach_rate < rhs.dna_mach_rate;
});

在 C++ 中使用数组 v 进行排序长度all并将它们按顺序排列,以便最低的 dna_mach_rate先走。

您需要 #include <algorithm>首先,自然。这也使用了 C++11 的特性,但此时 C++11 已经 5 岁了。

关于C++ 结构或数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38533121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com