19.11 指向数据成员的指针与普通数据指针的区别:不仅要给出成员本身的类型,还需要给出所属类的类型。
19.12
//定义成员指针,指向Screen类的cursor成员
Screen::pos Screen::*pm = &Screen::cursor;
//使用该指针获得Screen::cursor的值
Screen myscreen;
auto val = myscreen.*pm;
Screen *ps = &myscreen;
val = ps->*pm;
19.13
std::string Sales_data::*pdata;
19.14 auto pmf = &Screen::get_cursor; //合法,指向Screen的get_cursor成员函数的指针
pmf = &Screen::get; //合法,指向Screen中无参数版本的get成员函数
19.15 指向成员函数的指针,要给出成员函数本身的类型,还需要给出成员函数所属类的类型,并指明成员函数是否为const。
19.16
using Avg = double (Sales_data::*)() const;
Avg pavg = &Sales_data::avg_price;
19.17
using pmf1 = char (Screen::*)() const;
using pmf2 = char (Screen::*)(Screen::index, Screen::index) const;
using pmf3 = Screen& (Screen::*)();
using pmf4 = Screen& (Screen::*)(Screen::Directions);
19.18 用mem_fn实现:
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
unsigned int cnt(const vector<string> &svec)
{
unsigned int ret = count_if(svec.begin(), svec.end(), mem_fn(&string::empty));
return ret;
}
int main()
{
vector<string> svec = {"s1", "", "s3", ""};
auto c = cnt(svec);
cout << c << endl;
return 0;
}
19.19 需要先把Sales_data类的avg_price()成员函数改为public的
#include <iostream>
#include <vector>
#include <algorithm>
#include "Sales_data.h"
using namespace std;
using std::placeholders::_1;
bool high_price(Sales_data &item, double price)
{
return item.avg_price() > price;
}
vector<Sales_data>::iterator first_high_price(vector<Sales_data> &sv, double price)
{
auto f = bind(high_price, _1, price);
return find_if(sv.begin(), sv.end(), f);
}
int main()
{
vector<Sales_data> svec;
Sales_data record;
while (cin >> record) {
svec.push_back(record);
}
auto iter = first_high_price(svec, 10);
cout << *iter << endl;
return 0;
}