我是C ++的新程序员,我遇到了一个问题:
我有这堂课:
class car{
public:
//Default Constructor
car();
//Overload Constructor
car(string, int, float, float);
//Desctructor
~car();
//Access Functions
string getbrand() const;
int getyear() const;
float getkm() const;
float getprice() const;
//Mutator Functions
void setbrand(string);
void setyear(int);
void setkm(float);
void setprice(float);
private:
//variables
string newbrand;
int newyear;
float newkm;
float newprice;
};
//访问函数
string car::getbrand() const{
return newbrand;
}
int car::getyear() const{
return newyear;
}
float car::getkm() const{
return newkm;
}
float car::getprice() const{
return newprice;
}
所以,一旦我开始插入我的车,我就把它们放在一个矢量中:
void fillvector(vector<car>& newmyfleet){
string brand;
int year;
float km;
float price;
cout << "How many cars do you want in your fleet? ";
int fleetsize;
cin >> fleetsize;
for (int i = 0; i < fleetsize; i++){
cout << "Car Brand: ";
cin >> brand;
cout << "Car Year: ";
cin >> year;
cout << "Car Kms: ";
cin >> km;
cout << "Car Price: ";
cin >> price;
car newcar(brand, year, km, price);
newmyfleet.push_back(newcar);
cout << endl;
}
cout << endl;
}
所以我的问题是这样的:我如何按照矢量,按品牌对我的所有汽车进行分类?!! 我尝试过使用排序,但我不能......
这是我的最后一个解决方案:
//功能1
bool sortbybrand(car &c1, car &c2) { return c1.getbrand() < c2.getbrand(); }
//排序
void sbrand(const vector<car>& newmyfleet){
unsigned int size = newmyfleet.size(); //Number of cars
sort(newmyfleet.begin(), newmyfleet.end(), sortbybrand);
cout << "Sorting Cars by Brand\n\n " << endl;
for (unsigned int i = 0; i < size; i++){
cout << "Car: " << i + 1 << endl;
cout << "Car Brand: " << newmyfleet[i].getbrand() << endl;
cout << "Car Year: " << newmyfleet[i].getyear() << endl;
cout << "Car Kms: " << newmyfleet[i].getkm() << endl;
cout << "Car Price: " << newmyfleet[i].getprice() << endl;
cout << endl;
}
}