Hot*_*ead 1 c++ string file-io vector operator-overloading
在以下代码中:
using namespace std;
//ostream& operator<< (ostream& out,const string & str)
//{
// out << str.c_str();
// return out;
//}
int _tmain(int argc, _TCHAR* argv[])
{
ofstream file("file.out");
vector<string> test(2);
test[0] = "str1";
test[1] = "str2";
ostream_iterator<string> sIt(file);
copy(test.begin(), test.end(), sIt);
file.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
什么是重载的正确方法operator <<,使
copy(test.begin(), test.end(), sIt);工作.
我错过了什么?
编辑:我只是愚蠢......忘了包含"字符串"标题
谢谢!
您不需要重载operator<<以使用字符串,它已经知道如何处理它们.
std::copy( test.begin(), test.end(),
std::ostream_iterator<std::string>( file, "\n" ) );
Run Code Online (Sandbox Code Playgroud)
将产生:
str1
str2
Run Code Online (Sandbox Code Playgroud)
你想在那里完成任何不同/特殊的事吗?