c++ - 如何在函数指针列表上使用 std::for_each

标签 c++ boost

在下面的代码中,我如何使用 std::for_each 指令重写 for 循环。 我尝试使用 boost::lambda::_1boost::bind,但无法使其正常工作。

#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>

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;
}

欢迎任何帮助我解决这个问题的提示。

编辑:解决方案

#include <vector>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

int main() 
{ 
  std::vector<boost::function<int(const char*)> > processors; 
  processors.push_back(std::atoi); 
  processors.push_back(std::strlen); 

  const char data[] = "1.23"; 

  namespace bl = boost::lambda;
  std::for_each(processors.begin(), processors.end(),
      std::cout << bl::bind(bl::_1, data) << "\n");
}

最佳答案

如果 boost::lambda'\n' 而不是 endl 被允许,是否允许 下面的代码能达到目的吗?

namespace bl = boost::lambda;
std::for_each( processors.begin(), processors.end()
             , std::cout << bl::bind( bl::_1, data ) << '\n' );

关于c++ - 如何在函数指针列表上使用 std::for_each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5838679/

相关文章:

c++ - std::tr1 与 visual studio 2017

c++ - 汽车在我的游戏 C++ 中不能正确移动

c++ - "open"对于接受者来说意味着什么?

c++ - Win32 中的 RedrawWindow 和 UpdateWindow 有什么区别?

c++ - 引用和复制对象的返回类型

c++ - C++在程序执行中有cout和没有cout的时差

c++ - boost asio basic_socket 问题

c++ - boost 图书馆在行业中的接受度

gcc - boost::variant 与多态性,clang 和 gcc 的性能结果非常不同

c++ - 列出聚合的初始化 : when can it invoke copy constructor?