冒泡用一个充满类的数组排序。 [英] Bubble Sort with an array filled with classes.
问题描述
各位大家好,我在处理数组时很熟悉一个正常的冒泡排序,但我不确定如何实现一个排序,当我有一个数组充满了包含多个值的类时。
我需要进行一个名为Tree [100]的数组的冒泡排序,它在每个存储位置都有一个名为Christmas Tree的类,其值为Species,Height,trunkDiameter和costPerFoot。排序将需要按物种(这是一个字符串)排序不同的树,然后按costPerFoot(双倍)排序。
常规冒泡排序:
Hello everyone, I am familiar with a normal bubble sort when dealing with an array of number but I am unsure as how to implement a sort when I have an array that is filled with classes which hold multiple values.
I need to make a bubble sort that reaches into an array called Tree[100] which has in each storage location a class called Christmas Tree which have the values Species, Height, trunkDiameter, and costPerFoot. The sort will need to sort the different trees by species (which is a string) and then by costPerFoot (a double).
Regular bubble sort:
推荐答案
我有个主意。我有一个名为getSpecies()和getCost()的函数,它只返回在你所在的任何数组区域中找到的值。我可以......
I had an idea. I have a function called getSpecies() and getCost() which simply returns the values found in whatever array area your in. Could I...
这个想法将起作用......如果你传递这个类/结构的数组。现在你传入一个字符数组,然后尝试在其上使用类函数。字符不是类。你需要将Tree []传递给你的函数并对其进行排序。
更好的是,重载<和> Tree的运营商。您可以先比较名称 - 如果名称相同,您可以比较其他一些属性。
这将允许您使用模板编写通用的bubblesort:
That idea will work...if you pass an array of this class/struct. Right now you are passing in a character array, then trying to use a class function on it. Characters are not classes. You will want to pass a Tree[] to your function and sort that.
Even better, overload the < and > operators for Tree. You can compare names first - if the names are the same, you can compare some other attribute.
This will allow you to write a generalized bubblesort using templates:
这个想法会起作用...如果你传递一个数组这个类/结构。现在你传入一个字符数组,然后尝试在其上使用类函数。字符不是类。你需要将Tree []传递给你的函数并对其进行排序。
更好的是,重载<和> Tree的运营商。您可以先比较名称 - 如果名称相同,您可以比较其他一些属性。
这将允许您使用模板编写通用的bubblesort:
That idea will work...if you pass an array of this class/struct. Right now you are passing in a character array, then trying to use a class function on it. Characters are not classes. You will want to pass a Tree[] to your function and sort that.
Even better, overload the < and > operators for Tree. You can compare names first - if the names are the same, you can compare some other attribute.
This will allow you to write a generalized bubblesort using templates:
这篇关于冒泡用一个充满类的数组排序。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!