Problem Requirements
- Create a Menu class with private data members for item name and price
- Implement public member functions to access and modify these private members
- Read n menu items from input
- Display all items with prices below a specified threshold
- Identify and display the highest-priced item among the filtered results
Implementation
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class MenuItem {
public:
MenuItem(string dishName, double dishPrice)
: dishName(dishName), dishPrice(dishPrice) {}
string getDishName() const {
return dishName;
}
double getDishPrice() const {
return dishPrice;
}
private:
string dishName;
double dishPrice;
};
int main() {
int itemCount;
string dishName;
double dishPrice;
cin >> itemCount;
vector<MenuItem> menuList;
for (int i = 0; i < itemCount; i++) {
cin >> dishName >> dishPrice;
menuList.emplace_back(dishName, dishPrice);
}
double priceLimit;
cin >> priceLimit;
double highestPrice = -1;
string highestPriceItem;
for (int i = 0; i < itemCount; i++) {
if (menuList[i].getDishPrice() < priceLimit) {
cout << menuList[i].getDishName() << " "
<< menuList[i].getDishPrice() << endl;
if (menuList[i].getDishPrice() > highestPrice) {
highestPrice = menuList[i].getDishPrice();
highestPriceItem = menuList[i].getDishName();
}
}
}
cout << "max:" << highestPriceItem << " " << highestPrice;
return 0;
}
Sample Execution
Given the following input:
5
排骨 9.8
红烧肉 10.5
清蒸鱼 15
大白菜 5.5
鱼香茄子 6.8
10
The program outputs:
排骨 9.8
大白菜 5.5
鱼香茄子 6.8
max:排骨 9.8
Key Design Points
The MenuItem class uses a constructor with member initialization list to efficiently initialize private data members. The getter functions are marked as const to indicate they do not modify object state. The main function maintains the original input order during filtering, and the highest-priced item is tracked using simple comparison logic that preserves the first occurrence when prices are equal.