练习17.4
编写并测试你自己版本的findBook函数。
解答:
实现参考书中实现。
练习17.5
重写findBook,令其返回一个pair,包含一个索引和一个迭代器pair。
解答:
typedef pair<vector<Sales_data>::size_type, pair<vector<Sales_data>::const_iterator, vector<Sales_data>::const_iterator>> matches;
pair<size_t, pair<vector::const_iterator, vector::const_iterator>>
findBook(const vector<vector<Sales_data>> &files, const string &book)
{
pair<matches> ret; // initially empty
// for each store find the range of matching books, if any
for (auto it = files.cbegin(); it != files.cend(); ++it) {
// find the range of Sales_data that have the same ISBN
auto found = equal_range(it->cbegin(), it->cend(), book, compareIsbn);
if (found.first != found.second) // this store had sales
// remember the index of this store and the matching range
ret = make_pair(it - files.cbegin(), found);
}
return ret; // empty if no matches found
}
练习17.6
重写findBook,不使用tuple或pair。
解答:
template <typename T>
class matches_result{
public:
make_match(vector<T>::size_type i, vector<T>::const_iterator it1, vector<T>::const_iterator it2) : index(i), first(it1), second(it2){}
vector<T>::size_type index;
vector<T>::const_iterator first, second;
};
matches_result<Sales_data>
findBook(const vector<vector<Sales_data>> &files, const string &book)
{
matches_result<Sales_data> ret; // initially empty
// for each store find the range of matching books, if any
for (auto it = files.cbegin(); it != files.cend(); ++it) {
// find the range of Sales_data that have the same ISBN
auto found = equal_range(it->cbegin(), it->cend(), book, compareIsbn);
if (found.first != found.second) // this store had sales
// remember the index of this store and the matching range
ret.make_match(it - files.cbegin(), found.first, found.second);
}
return ret; // empty if no matches found
}
这里构造了一个保存数据的类来进行记录。
当需要对结果进行处理的时候,这个类可以包含在处理类中。
练习17.7
解释你更倾向于哪个版本的findBook,为什么。
解答:
我会更偏向于使用tuple的版本。
易与理解,且代码实现比较简单。
练习17.8
在本节最后一段代码中,如果我们将Sales_data()作为第三个参数传递给accumulate,会发生什么?
解答:
先看一下accumulate的等价实现
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}
Sales_data的+=操作符
Sales_data& Sales_data::operator+=(const Sales_data &rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
Sales_data的<<操作符
ostream &operator<<(ostream &os, const Sales_data &item)
{
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price();
return os;
}
从上面可以看出,替换为Sales_data(), 序运行上是没有太大的影响,只不过会在输出的时候,本来应该显示bookNo的地方是空的。