根据属性C 对对象进行排序
sort an array of objects based on property c++
可能的重复:
C 与结构排序
#include <iostream>
using namespace std;
class fish{
private:
int size;
int price;
public:
fish()
{
size=0;
price=0;
}
void set_price(int x)
{
price=x;
}
void set_size(int g)
{
size=g;
}
int get_size()
{
return size;
}
int get_price()
{
return price;
}
void display()
{
cout<<" Fish price is "<<price<<" Fish size is "<<size<<endl;
}
void sort(fish h[5])
{
for (int o=0;o<=5;o++)
{
fish temp;
temp.set_price(0);
if (h[o].get_price()>h[o+1].get_price())
{
temp.get_price()=h[o].get_price();
h[o].get_price()=h[o+1].get_price();
h[o+1].get_price()=temp.get_price();
}
}
}
};
void main()
{
fish a;
fish b[5];
a.set_size(500);
a.set_price(2);
a.display();
for (int i=0;i<=5;i++)
{
b[i].set_size(i*2);
b[i].set_price(i*100);
}
for (i=0;i<=5;i++)
b[i].display();
}
我想找出如何发送数组b
并对其进行排序。我还要询问破坏者以及可以将它们放入我的代码中的地方。
在排序时要交换鱼,应该写这
fish tmp = h[o];
h[o] = h[o+1];
h[o+1] = tmp;
您是根据鱼价进行排序的,但是应该分类的是整个鱼。
在您的另一个问题上,此代码中不需要驱动器。您的鱼类课程不需要进行任何"清理",因此不需要破坏者。
如果您想通过给定元素对数组进行排序,那么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);
}
}
这是用于对数组进行排序的常见QuickSort函数。只需替换正确的变量以表示您的数据,例如t *元素变成鱼 *东西,t t =元素[第一个]变为双重价格= fitf [first]等。
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 对象接收堆栈溢出异常 c++ 的排序向量
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 排序谓词没有传递对索引对象的引用?
- 使用指针指向对象C++对向量进行排序
- 按类成员的顺序对包含类对象的C++向量进行排序
- 无法使用接口类型对priority_queue中的对象进行排序<T>
- 基于不同字段的对象向量的排序功能
- 基于3个对象的自定义排序
- 尝试使用比较运算符对对象向量进行排序
- C++排序的对象集
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- q排序类对象的列表
- std::atexit 从全局对象的构造函数调用时的排序
- 尝试对对象数组进行排序时程序终止
- std::排序为排序自定义对象时出现的向量引发错误
- 使用sort()算法C 排序对象列表
- 使用std::sort与自定义排序对象和数据类型模板-寻找正确的语法
- 快速方法部分排序对象
- 如何在动态内存中排序对象列表,在c++中使用泛型向量