2011-05-02 43 views
1
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 <<); 

回答

15

因为这是一个成员函数,并且for_each需要一个带有单个参数的函数对象。

你必须写自己的功能:

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

另一种方法是混合std::mem_funstd::bind1st(或任何更好的C++ 0x /升压替代品)来生成功能。

但是,最好的办法是使用std::copystd::ostream_iterator

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

的for_each接受一个函数作为最后一个参数应用在范围内的元素, 定义一个函数应该做的事情,你有什么

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

然后

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

如果这是你正在尝试...

3

std::for_each需要一个函数,它有一个参数,你正在迭代的容器的元素。但是,operator <<需要两个参数,即运算符的左侧和右侧。所以事情不排队。

您必须以某种方式绑定ostream参数,以便您再次下到单个参数。 boost::bind是一种方法,或者您可以定义一个自定义的单个参数函数并传递该函数。

相关问题