(1)定义一个苹果类型,具有品牌,重量和甜度三个属性,以及必要的成员函数; (2)主函数main()使用STL算法和lambda表达式,筛选出符合条件(比如某个品牌,或是重量大于50克且甜度大于9)的苹果。 输入格式: 见输入样例。 输出格式: 见输出样例。 输入样例: 第一行输入苹果数量n 然后每行输入一个苹果,共n行; 然后输入要筛选的品牌;示例中是HFS; 然后输入高品质苹果的条件:重量和甜度,示例中是重量大于50.0, 甜度大于9.0; 6 XJ 50.8 9.2 XJ 60.5 10.2 HFS 50.2 10.5 HFS 55.8 10.9 TX 45.8 9.5 TX 40.0 8.5 HFS 50.0 9.0 输出样例: 先输出:指定品牌的所有苹果(品牌、重量、甜度用空格隔开);空行; 然后输出:所有高品质苹果(品牌、重量、甜度用空格隔开) ;空行; HFS: HFS 50.2 10.5 HFS 55.8 10.9 High quality: XJ 50.8 9.2 XJ 60.5 10.2 HFS 50.2 10.5 HFS 55.8 10.9
时间: 2024-03-08 11:47:32 浏览: 121
以下是C++代码实现:
```cpp
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Apple {
public:
string brand;
double weight;
double sweetness;
Apple(string brand, double weight, double sweetness) {
this->brand = brand;
this->weight = weight;
this->sweetness = sweetness;
}
bool operator()(const Apple &a) {
return a.brand == brand && a.weight > 50 && a.sweetness > 9;
}
};
int main() {
int n;
cin >> n;
vector<Apple> apples;
for (int i = 0; i < n; i++) {
string brand;
double weight, sweetness;
cin >> brand >> weight >> sweetness;
apples.emplace_back(brand, weight, sweetness);
}
string target_brand;
cin >> target_brand;
double target_weight, target_sweetness;
cin >> target_weight >> target_sweetness;
cout << "Specified brand:" << endl;
for_each(apples.begin(), apples.end(), [&](const Apple &a) {
if (a.brand == target_brand) {
cout << a.brand << " " << a.weight << " " << a.sweetness << endl;
}
});
cout << endl;
cout << "High quality:" << endl;
vector<Apple> high_quality;
copy_if(apples.begin(), apples.end(), back_inserter(high_quality), Apple(target_brand, target_weight, target_sweetness));
for_each(high_quality.begin(), high_quality.end(), [](const Apple &a) {
cout << a.brand << " " << a.weight << " " << a.sweetness << endl;
});
cout << endl;
return 0;
}
```
阅读全文