如何在c#中对上升的字符串数组进行排序,我希望使用诸如std::C++中的排序:
std::sort(population.begin(), population.end())我需要整理一下表。列表中的对象是Genome类的实例。我在该类中重载了操作符<和运算符>。
class Genome
{
public List<double> weights;
public double fitness;
public Genome()
{
fitness = 0.0;
weights = new List<double>();
}
public Genome(List<double> weights, double fitness) {
this.weights = weights;
this.fitness = fitness;
}
public static bool operator <(Genome lhs, Genome rhs)
{
return (lhs.fitness < rhs.fitness);
}
public static bool operator >(Genome lhs, Genome rhs) {
return (lhs.fitness > rhs.fitness);
}
}人口就是这样被宣布的:
List<Genome> population = new List<Genome>();如何对这个数组进行排序??可以使用操作符重载操作符<类似在C++中吗?
发布于 2016-07-17 18:36:58
population.OrderBy(x => x.weights); 或者:
population.OrderByDescending(x => x.fitness); 发布于 2016-07-17 18:37:37
与依赖于C++进行排序的operator<不同,C#依赖于类对IComparable<T>的实现,或者使用传递给Sort方法的外部比较器:
class Genome : IComparable<Genome> {
public int CompareTo(Genome other) {
return fitness.CompareTo(other.fitness);
}
}可以使用
<的操作符重载吗,就像在C++中那样?
IComparable<T>比<稍微复杂一些,因为当对象相等时,它返回零。您可以使用<和>表示相同的逻辑,但是直接实现IComparable<T>接口更容易。
发布于 2016-07-17 18:44:15
定义对象顺序(<和>)的方式不适合C#。
您需要实现IComparable接口。它只有一种方法:
public interface IComparable
{
int CompareTo(object o);
}CompareTo方法用于将对象与其他对象进行比较。它返回一个数字:
例如:
class Paper: IComparable
{
public int width;
public int height;
public int CompareTo(object o)
{
Paper p = o as Paper;
if (p!=null)
{
return this.width*this.height-p.width*p.height
}
}在你的情况下,你只需要把这个还给你。
https://stackoverflow.com/questions/38424626
复制相似问题