3.6. 练习

You can buy solutions to all exercises in this book as a ZIP file.

  • 简化以下程序,将函数对象 divide_by 转换为一个函数,并将 for 循环替换为用一个标准的 C++ 算法来输出数据:
  1. #include <algorithm>
  2. #include <functional>
  3. #include <vector>
  4. #include <iostream>
  5.  
  6. class divide_by
  7. : public std::binary_function<int, int, int>
  8. {
  9. public:
  10. int operator()(int n, int div) const
  11. {
  12. return n / div;
  13. }
  14. };
  15.  
  16. int main()
  17. {
  18. std::vector<int> numbers;
  19. numbers.push_back(10);
  20. numbers.push_back(20);
  21. numbers.push_back(30);
  22.  
  23. std::transform(numbers.begin(), numbers.end(), numbers.begin(), std::bind2nd(divide_by(), 2));
  24.  
  25. for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it)
  26. std::cout << *it << std::endl;
  27. }
  • 下载源代码
    • 简化以下程序,将两个 for 循环都替换为标准的 C++ 算法:
  1. #include <string>
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. int main()
  6. {
  7. std::vector<std::string> strings;
  8. strings.push_back("Boost");
  9. strings.push_back("C++");
  10. strings.push_back("Libraries");
  11.  
  12. std::vector<int> sizes;
  13.  
  14. for (std::vector<std::string>::iterator it = strings.begin(); it != strings.end(); ++it)
  15. sizes.push_back(it->size());
  16.  
  17. for (std::vector<int>::iterator it = sizes.begin(); it != sizes.end(); ++it)
  18. std::cout << *it << std::endl;
  19. }
  • 下载源代码
    • 简化以下程序,修改变量 processors 的类型,并将 for 循环替换为标准的 C++ 算法:
  1. #include <vector>
  2. #include <iostream>
  3. #include <cstdlib>
  4. #include <cstring>
  5.  
  6. int main()
  7. {
  8. std::vector<int(*)(const char*)> processors;
  9. processors.push_back(std::atoi);
  10. processors.push_back(reinterpret_cast<int(*)(const char*)>(std::strlen));
  11.  
  12. const char data[] = "1.23";
  13.  
  14. for (std::vector<int(*)(const char*)>::iterator it = processors.begin(); it != processors.end(); ++it)
  15. std::cout << (*it)(data) << std::endl;
  16. }