对类的元素进行排序并在类中查找不同的元素

Sorting an element of class and finding different elements in class

本文关键字:元素 查找 排序      更新时间:2023-10-16
#include<iostream>
using namespace std;
class Lek{
    private:
        int sifra;
        string ime;
        string proizvoditel;
        int cena;
        int kolicina;
    public:
        Lek(){
        }
        void postavuvanje(int s, string i, string p, int c, int k){
            sifra = s;
            ime = i;
            proizvoditel = p;
            cena = c;
            kolicina = k;
        }
        int vratiSifra(){
            return sifra;
        }
        string vratiIme(){
            return ime;
        }
        string vratiProizvoditel(){
            return proizvoditel;
        }
        int vratiCena(){
            return cena;
        }
        int vratiKolicina(){
            return kolicina;
        }
        void pecati(){
            cout << sifra << " " << ime << " " << proizvoditel << " " << cena << " " << kolicina << endl;
        }
};
int main(){
    Lek Apteka[100];
    int n;
    cout << "Vnesi go brojot na lekovi" << endl;
    cin >> n;
    int sifra;
    string ime;
    string proizvoditel;
    int cena;
    int kolicina;
    // here we are inputting the values for the array of objects.
    for(int i = 0; i < n; i++){
        cin >> sifra;
        cin >> ime;
        cin >> proizvoditel;
        cin >> cena;
        cin >> kolicina;
        Apteka[i].postavuvanje(sifra, ime, proizvoditel, cena, kolicina);
    }
    // this is part to find the name of the element with the lowest price.
    int najmala_cena = Apteka[0].vratiCena();
    int index = 0;
    for(int i = 1; i < n; i++){
        if(Apteka[i].vratiCena() < najmala_cena){
            najmala_cena = Apteka[i].vratiCena();
            index = i;
        }
    }
    cout << Apteka[index].vratiIme() << endl;
    return 0;
}

我已经设法解决了找到价格最低的元素的问题。但是,我在按价格(cena)对元素进行排序时遇到问题。此外,我必须找到所有具有"proizvoditel"X"的元素,并找出它有多少个不同的名称(ime)。

对于按价格(cena)对元素进行排序,我认为这是不言自明的。但是由于我的英语在第二个问题上不是那么好,这里基本上是一个快速的例子。

假设我们有以下用户输入:

1
PillX
HospitalY
125
2
2
PillY
HospitalY
225
4
3
PillZ
HospitalY
590
1
4
PillX
HospitalY
125
8

所以,基本上,这些是类的 4 个对象的属性,我们对所有药丸都有相同的"proizvoditel",称为"HospitalY",我们必须找到它有多少种不同的药丸,所以它有 3 个,因为 PillX 已经存在并且不第二次计算。

最简单的方法是重载您自己的自定义排序运算符并在#include <algorithm>中使用std::sort

bool cena_comp(const Lek &a, const Lek &b) { return a.vratiCena() < b.vratiCena(); }

使用它:

bool (*cena_comp_ptr)(const Lek &a, const Lek &b) = cena_comp;
Lek *beg = &Apteka[0], *end = &Apteka[n];
sort(beg, end, cena_comp_ptr);