对类的元素进行排序并在类中查找不同的元素
Sorting an element of class and finding different elements in class
#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);
相关文章:
- 使用堆查找第K个最大元素的时间复杂性
- 查找矩阵C++中每一列和每一行的最小和最大元素
- C++如何在向量中查找最常见的元素
- 查找两个排序向量中共有的元素
- 在对向量中查找元素的索引
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 查找矩阵中单元格的相邻元素
- 为什么使用数组元素查找最大数字的程序不起作用?
- 查找第一个数组中不存在的元素
- 查找最小的下一个更大的元素
- 在最小堆中查找最大元素
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- set::find 查找不存在的元素
- 在集合中查找使用结构C++的元素
- 从斐波那契序列 c++ 中的数组中查找正确的元素时出错
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 查找数组中指示性较大但数组中值较小的元素
- C++结构集无法按元素查找/擦除
- 如何在OpenCV中使用Matlab的512元素查找表数组?
- 使用数组的元素查找总和'k'