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 <<);
Run Code Online (Sandbox Code Playgroud)
Eti*_*tel 15
因为那是一个成员函数,并且for_each想要一个带有单个参数的函数对象.
你必须编写自己的函数:
void print_to_stdout(int i)
{
std::cout << i;
}
std::for_each(my_ints.begin(), my_ints.end(), print_to_stdout);
Run Code Online (Sandbox Code Playgroud)
另一种方法是混合std::mem_fun和std::bind1st(或任何更好的C++ 0x/boost替代方案)来生成该函数.
但是,最好的办法是使用std::copy一个std::ostream_iterator:
std::copy(my_ints.begin(), my_ints.end(), std::ostream_iterator<int>(std::cout));
Run Code Online (Sandbox Code Playgroud)