3.6. 练习
You can buy solutions to all exercises in this book as a ZIP file.
- 简化以下程序,将函数对象
divide_by
转换为一个函数,并将for
循环替换为用一个标准的 C++ 算法来输出数据:
- #include <algorithm>
- #include <functional>
- #include <vector>
- #include <iostream>
- class divide_by
- : public std::binary_function<int, int, int>
- {
- public:
- int operator()(int n, int div) const
- {
- return n / div;
- }
- };
- int main()
- {
- std::vector<int> numbers;
- numbers.push_back(10);
- numbers.push_back(20);
- numbers.push_back(30);
- std::transform(numbers.begin(), numbers.end(), numbers.begin(), std::bind2nd(divide_by(), 2));
- for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it)
- std::cout << *it << std::endl;
- }
- 下载源代码
- 简化以下程序,将两个
for
循环都替换为标准的 C++ 算法:
- 简化以下程序,将两个
- #include <string>
- #include <vector>
- #include <iostream>
- int main()
- {
- std::vector<std::string> strings;
- strings.push_back("Boost");
- strings.push_back("C++");
- strings.push_back("Libraries");
- std::vector<int> sizes;
- for (std::vector<std::string>::iterator it = strings.begin(); it != strings.end(); ++it)
- sizes.push_back(it->size());
- for (std::vector<int>::iterator it = sizes.begin(); it != sizes.end(); ++it)
- std::cout << *it << std::endl;
- }
- 下载源代码
- 简化以下程序,修改变量 processors 的类型,并将
for
循环替换为标准的 C++ 算法:
- 简化以下程序,修改变量 processors 的类型,并将
- #include <vector>
- #include <iostream>
- #include <cstdlib>
- #include <cstring>
- int main()
- {
- std::vector<int(*)(const char*)> processors;
- processors.push_back(std::atoi);
- processors.push_back(reinterpret_cast<int(*)(const char*)>(std::strlen));
- const char data[] = "1.23";
- for (std::vector<int(*)(const char*)>::iterator it = processors.begin(); it != processors.end(); ++it)
- std::cout << (*it)(data) << std::endl;
- }