I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &);
is not defined leading to compiler errors. The following code illustrates the problem:
#include <iostream>
#include <string>
int main()
{
std::string message = "Hello World!\n";
// This works
std::cout << message;
// Compiler error
std::cout.operator <<(message);
}
I thought that both statements should appear identical to the compiler. Apparently they are not. So what is the difference then?
Solved
As Tomalak and Prasoon indicated I needed to call this function:
std::ostream& operator<<(std::ostream&, const std::string&);
So the following sample will work:
#include <iostream>
#include <string>
int main()
{
std::string message = "Hello World!\n";
operator<<(std::cout, message);
}
Concerning my original goal (to use for_each to print a vector of strings): It seems like it's better to use std::copy
with std::ostream_iterator
as illustrated here: How do I use for_each to output to cout?