Как использовать std :: for_each в списке указателей на функции - PullRequest
3 голосов
/ 30 апреля 2011

В следующем коде, как я могу переписать цикл for с помощью инструкции std :: for_each.Я пытался использовать boost::lambda::_1, boost::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");
}

Ответы [ 3 ]

2 голосов
/ 30 апреля 2011

Если разрешено boost::lambda и '\n' вместо endl, следующий код соответствует цели?

namespace bl = boost::lambda;
std::for_each( processors.begin(), processors.end()
             , std::cout << bl::bind( bl::_1, data ) << '\n' );
1 голос
/ 30 апреля 2011

Возможно, вам будет проще использовать BOOST_FOREACH :

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

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

    const char data[] = "1.23";

    BOOST_FOREACH(ProcessorFunc& proc, processors)
    {
        std::cout << proc(data) << std::endl;
    }

}

Или вы можете использовать ранжированный цикл for из C ++ 0x.

1 голос
/ 30 апреля 2011
void blah(int (*func)(const char *), const char *data)
{
    std::cout << func(data) << std::endl;
};

...

std::for_each(processors.begin(), processors.end(), boost::bind(blah, _1, data));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...