C++ Primer(第5版) 练习 10.17
练习 10.17 重写10.3.1节练习10.12(第345页)的程序,在对sort的调用中使用lambda来代替函数compareIsbn。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
/*************************************************************************
> File Name: ex10.17.cpp
> Author:
> Mail:
> Created Time: Sat 02 Mar 2024 08:11:38 PM CST
************************************************************************/
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Sales_data{
Sales_data(const string &s, unsigned n, double p):
bookNo(s), units_sold(n), price(p), revenue(p * n) {}
Sales_data(): Sales_data("", 0, 0) {}
Sales_data(string s): Sales_data(s, 0, 0) {}
Sales_data(istream &);
friend ostream &print(ostream&, const Sales_data&);
friend istream &read(istream&, Sales_data&);
string isbn() const;
Sales_data& combine(const Sales_data&);
double avg_price() const;
string bookNo;
unsigned units_sold = 0;
double price = 0.0;
double revenue = 0.0;
};
Sales_data::Sales_data(istream &in){
read(in, *this);
}
string Sales_data::isbn() const{
return this->bookNo;
}
Sales_data& Sales_data::combine(const Sales_data &rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
double Sales_data::avg_price() const{
if(units_sold){
return revenue / units_sold;
}
else{
return 0;
}
}
Sales_data add(const Sales_data &sd1, const Sales_data &sd2){
Sales_data t = sd1;
t.combine(sd2);
return t;
}
ostream &print(ostream &output, const Sales_data &sd){
output<<sd.bookNo<<" "<<sd.units_sold<<" "<<sd.price<<" "<<sd.revenue<<" "<<sd.avg_price()<<endl;
return output;
}
istream &read(istream &input, Sales_data &sd){
input>>sd.bookNo>>sd.units_sold>>sd.price;
sd.revenue = sd.price * sd.units_sold;
return input;
}
bool compareIsbn(const Sales_data &s1, const Sales_data &s2){
return s1.isbn() < s2.isbn();
}
int main(){
vector<Sales_data> sales;
Sales_data temp;
cout<<"Enter sales data: "<<endl;
while(read(cin, temp)){
sales.push_back(temp);
}
cout<<endl;
cout<<"Original sales data: "<<endl;
for(const auto s : sales){
print(cout, s);
}
cout<<endl;
stable_sort(sales.begin(), sales.end(), [](const Sales_data &s1, const Sales_data &s2){ return s1.isbn() < s2.isbn(); });
cout<<"New sort: "<<endl;
for(const auto s : sales){
print(cout, s);
}
cout<<endl;
return 0;
}