Ramadheer Singh
Ramadheer Singh

Reputation: 4234

why can't I put "cout <<" as a function argument in for_each?

std::vector<int> my_ints;
my_ints.push_back(1);
my_ints.push_back(2);
my_ints.push_back(3);
my_ints.push_back(4);

std::for_each(my_ints.begin(), my_ints.end(), std::cout.operator <<); 

Upvotes: 1

Views: 560

Answers (3)

Etienne de Martel
Etienne de Martel

Reputation: 36986

Because that's a member function, and for_each wants a function object that takes a single parameter.

You'll have to write your own function:

void print_to_stdout(int i)
{
    std::cout << i;
}
std::for_each(my_ints.begin(), my_ints.end(), print_to_stdout); 

Another alternative is to mix std::mem_fun and std::bind1st (or any of the better C++0x/boost alternatives) to generate that function.

But the best would be to use std::copy with a std::ostream_iterator:

std::copy(my_ints.begin(), my_ints.end(), std::ostream_iterator<int>(std::cout));

Upvotes: 15

Dennis Zickefoose
Dennis Zickefoose

Reputation: 10979

std::for_each requires a function that has a single parameter, the element of the container you are iterating over. However, operator << requires two parameters, the left hand side and the right hand side of the operator. So things don't line up.

You have to somehow bind the ostream parameter so that you are down to a single parameter again. boost::bind is one way, or you can just define a custom, single argument function and pass that.

Upvotes: 3

Umut Tabak
Umut Tabak

Reputation: 1942

for_each accepts a function as the last argument to apply on the elements of the range, defining a function should do what you what

void print(int i){
  cout << i << endl;
}

then

for_each(vector.begin(), vector.end(), print)

if this is what you are trying...

Upvotes: 2

Related Questions