menu-sort
时间: 2023-06-30 18:17:30 浏览: 62
menu-sort 是一个将菜单按照价格或名称进行排序的功能。它可以让用户按照自己的需求对菜单进行排序,便于查找和选择。
下面是一个使用 C++ 实现的 menu-sort 的示例程序:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct Dish {
string name;
int price;
};
bool cmp_by_name(const Dish& a, const Dish& b) {
return a.name < b.name;
}
bool cmp_by_price(const Dish& a, const Dish& b) {
return a.price < b.price;
}
int main() {
vector<Dish> menu = {
{"Beef Noodle", 10},
{"Fried Rice", 8},
{"Hamburger", 12},
{"Hot Dog", 6},
{"Pizza", 15},
};
cout << "Original menu:" << endl;
for (const auto& d : menu) {
cout << d.name << "\t" << d.price << endl;
}
char choice;
cout << "Sort by name or price? (n/p): ";
cin >> choice;
if (choice == 'n') {
sort(menu.begin(), menu.end(), cmp_by_name);
cout << "Sorted by name:" << endl;
} else {
sort(menu.begin(), menu.end(), cmp_by_price);
cout << "Sorted by price:" << endl;
}
for (const auto& d : menu) {
cout << d.name << "\t" << d.price << endl;
}
return 0;
}
```
该程序定义了一个 Dish 结构体,包括菜名和价格两个属性。然后定义了两个比较函数 `cmp_by_name` 和 `cmp_by_price`,分别用于按照菜名和价格进行排序。在主函数中,首先输出原始菜单,然后根据用户的选择使用不同的比较函数进行排序,并输出排序后的结果。