Reputation: 47
The function below displays all the elements in the Car vector in the following order:
Car: #1
Make: BMW
Model: X6
Price (£): 50000
Car: #2
Make: Honda
Model: Jazz
Price (£): 13000
Car: #3
Make: Mazda
Model: 3
Price (£): 20000
etc
I would like to compare all the cars in the vector based on the price in order to find out which car is cheaper out of all the cars. Is there a Comparable method to compare the certain fields within the same vector?
This is a sample code:
void displayCars(vector<Car> carVec)
{
if (!carVec.empty())
{
cout << "Current Inventory:\n";
for (unsigned int count = 0; count < carVec.size(); count++)
{
cout << "\t\t\tCar: #" << (count + 1) << endl
<< "\t\t___________________________\n\n"
<< "Make: " << carVec[count].getMake() << endl
<< "Model: " << carVec[count].getModel() << endl
<< "Price (£): " << carVec[count].getPrice() << endl
<< endl << endl;
}
}
}
Upvotes: 1
Views: 122
Reputation:
Use std::min_element:
auto min = std::min_element( begin(carVec), end(carVec),
[](const auto& lh, const auto& rh) {
return lh.getPrice() < rh.getPrice();
});
std::cout << "Cheapest is: " << min->getModel() << "\n";
Upvotes: 2
Reputation: 483
If you will always be sorting by the price, then you could do this:
class Car {
public:
int price;
std::string make;
std::string model;
int index;
bool operator<(Car const& otherCar) const;
}
bool Car::operator<(Car const& otherCar) const
{
return price < otherCar.price;
}
If you do it this way, then all the standard sorting algorithms on vectors will automatically sort using the price. Otherwise you can define separate functions on each thing you want to sort by:
bool IsCheaper(Car const& Car1, Car const& Car2)
{
return Car1.price < Car2.price
}
Upvotes: 0