C++ 基于属性c+;对对象数组进行排序+;
可能重复:C++ 基于属性c+;对对象数组进行排序+;,c++,class,sorting,C++,Class,Sorting,可能重复: #包括 使用名称空间std; 分类鱼{ 私人: 整数大小; 国际价格; 公众: 鱼() { 尺寸=0; 价格=0; } 无效集合价格(整数x) { 价格=x; } 空集大小(整数g) { 尺寸=克; } int get_size() { 返回大小; } int get_price() { 退货价格; } 无效显示() { cout要在排序时交换鱼,您应该写以下内容 fish tmp = h[o]; h[o] = h[o+1]; h[o+1] = tmp; 你是根据鱼的价格来分类的
#包括
使用名称空间std;
分类鱼{
私人:
整数大小;
国际价格;
公众:
鱼()
{
尺寸=0;
价格=0;
}
无效集合价格(整数x)
{
价格=x;
}
空集大小(整数g)
{
尺寸=克;
}
int get_size()
{
返回大小;
}
int get_price()
{
退货价格;
}
无效显示()
{
cout要在排序时交换鱼,您应该写以下内容
fish tmp = h[o];
h[o] = h[o+1];
h[o+1] = tmp;
你是根据鱼的价格来分类的,但是应该对整条鱼进行分类
关于你的另一个问题,在这段代码中不需要析构函数。你的fish类不需要做任何“清理”,所以它不需要析构函数。如果你想按给定的元素对数组排序,STL容器应该很好,否则我会使用这个方法
template<class T>
void quickSort(T * elements, unsigned int first, unsigned int last)
{
if(first < last) //make sure params are in bounds
{
T t = elements[first]; //t is PIVOT
unsigned lastLow = first; //create last low item
unsigned i; //used for loop/swapping
for(i = first + 1; i <= last; i++) //run through entire bounds
if(elements[i] < t) //if elements is less than Low
{
<< " adding one onto lastLow...\n";
lastLow++; //move lastLow up one
swap(elements,lastLow, i); //swap lastlow and i
}
swap(elements,first, lastLow); //swap first and lastlow
if(lastLow != first) //if lastlow is not first element
quickSort(elements, first, lastLow - 1);
if(lastLow != last) //if lastlow is not last element
quickSort(elements, lastLow + 1, last);
}
}
模板
无效快速排序(T*元素,先无符号整数,后无符号整数)
{
if(first 对于(i=first+1;i std::sort是您的朋友thish[o]。get\u price()=h[o+1]。get\u price();
不会改变任何东西。即使它改变了,它也会随机重新分配产品价格。它只会给我这样一个错误C2106:“=”:左操作数必须是l值\\帮助我改变h[o]。get\u price()=h[o+1]。get\u price()这一个你在这段代码中不需要任何析构函数。你的fish
类不需要做任何“清理”,所以不需要析构函数。std::swap工作得很好的确,std::sort也可以,但看起来user1791233想为自己做些事情。
template<class T>
void quickSort(T * elements, unsigned int first, unsigned int last)
{
if(first < last) //make sure params are in bounds
{
T t = elements[first]; //t is PIVOT
unsigned lastLow = first; //create last low item
unsigned i; //used for loop/swapping
for(i = first + 1; i <= last; i++) //run through entire bounds
if(elements[i] < t) //if elements is less than Low
{
<< " adding one onto lastLow...\n";
lastLow++; //move lastLow up one
swap(elements,lastLow, i); //swap lastlow and i
}
swap(elements,first, lastLow); //swap first and lastlow
if(lastLow != first) //if lastlow is not first element
quickSort(elements, first, lastLow - 1);
if(lastLow != last) //if lastlow is not last element
quickSort(elements, lastLow + 1, last);
}
}