对对象数组进行排序

Sorting arrays of objects

本文关键字:排序 数组 对象      更新时间:2023-10-16
class Medicine{
protected:
    int id;
    int stock;
    string name;
    int concentration;
public:
    Medicine(); 
    Medicine(int id,int s,const string n,int c);        
    Medicine(const Medicine& m);                
    Medicine& operator=(const Medicine& m);     
    virtual ~Medicine();    
        int getStock() const;   
    int getConcentration() const;}; 

模块1

    template<typename T> class Vector
    {
    private:
        T* Elems;
        int Size;
        int Capacity;
    public:
        Vector()
    ~Vector()
    void add(T e)
    void remove(int pos)
    int getSize() const
    int getCapacity() const
    T get(int pos) const;}
template <typename T>
    T Vector<T>::get(int pos) const
    {
        if (pos < 0 || pos >= this->getSize())
            return NULL;
        return this->Elems[pos];
    }
模块2

class MedRepo :
public:~MedRepo();
 void addMed(Medicine s);
     void upgrade(Medicine s);
Medicine* findById(int medId) ;
virtual void removeMed(int id) ;
int getNrMeds();
Vector<Medicine*> getAll() ;
protected:
    Vector<Medicine*> MedList;
};

模块3

typedef int (*comparefunction)(const void*, const void*);
int compareSA(const Medicine* e1, const Medicine* e2){
    int q1 = (*(Medicine **) e1)->getStock();
    int q2 = (*(Medicine **) e2)->getStock();
    if (q1 < q2){
             return -1;
         }
    else{
        if (q1>q2){
            return 1;
        }
        return 0;
    }
}
模块4

这是我代码的一部分,我想做的是根据一些标准对对象进行排序,其中一个是第四个模块中的那个。从这周开始,我一直在研究课程,我发现了一些类似的问题,但我不明白整个排序的过程。我刚刚读了一些关于std:sortstd::stable_sort的东西,但我不知道如何将它们用于我的数据。我现在只有:

Vector<Medicine*>* Control::sortByStockAsc(){
    Vector<Medicine*> all =repo->getAll();

任何想法,建议,帮助吗?

首先:扔掉你自己的vector类(它有bug)通过查看成员的类型就很明显了)。使用std::vector<T>

如果你真的想继续使用它想使用std::sort,您需要为它实现迭代器。如果你只是从c++开始,这可能是一个真正的挑战(有很多文章,整个帮助库和书籍章节专门讨论它)。

如果您不想使用std::sort,并希望保留自己的Vector,为你的容器实现一个排序算法。

理想情况:将operator<(const Medicine&, const Medicine&) for Medicine作为严格弱排序关系实现并使用这样的:

#include <vector>
#include <algorithm>
std::vector<Medicine> mv;
std::sort(begin(mv), end(mv));

如果有更多的可能性来比较Medicine,则实现函数或自由函数:

struct LessCmpMedicineByName {
  bool operator()(const Medicine&, const Medicine&) const;
};
struct LessCmpMedicineById {
  bool operator()(const Medicine&, const Medicine&) const;
};
// use
std::sort(begin(mv), end(mv), LessCmpMedicineByName());
// or with a lambda
std::sort(begin(mv), end(mv), [](const Medicine& x, const Medicine& y) {
  // comparison code here
  return true;
});

不要丢弃vector。制作自己的容器有很多优点。要使任何排序算法工作,必须仔细定义排序标准。

任何排序操作只需要一个>操作符就可以满足您的条件,必须具有以下属性:

for any a b and c, if a > b and b > c then it must be that a > c
for any a, a > a must be false.

等式定义为:

(!(a > b ) && !( b > a ))

相等条件可以(也应该)被编码到排序算法中。您不需要为您的排序条件专门定义相等操作符。

如果输入相等,则不需要常规排序算法来保持输入的顺序。在稳定排序算法中,任何在输入中相等的输入必须在输出中以相同的相对顺序发出。例如,如果您仅按数字对扑克牌进行排序,并且您的输入是5h 4d 5,则稳定排序的输出必须是4d 5h5 s。对于非稳定排序,它可以输出4d ~ 5s ~ 5h。

稳定排序稍微慢一些。通常不需要稳定的排序