[英]Copying words from one file to another in cpp
I'm trying to copy words from one file to another in cpp, here's my code : 我正在尝试将单词从一个文件复制到cpp中的另一个文件,这是我的代码:
int main()
{
string from, to;
cin >> from >> to;
ifstream ifs(from);
ofstream ofs(to);
set<string> words(istream_iterator<string>(ifs), istream_iterator<string>());
copy(words.begin(), words.end(), ostream_iterator<string>(ofs, "\n"));
return !ifs.eof() || !ofs;
}
this way I get a compilation error : 这样我得到一个编译错误:
expression must have class type
at the line of where I call copy() 在我调用copy()的那一行
If I change the construction of the iterators to the following it works : 如果我将迭代器的构造更改为以下内容,则它会起作用:
set<string> words{ istream_iterator<string>{ ifs }, istream_iterator<string>{} };
I thought choosing between () and {} when initializing objects in cpp is just a matter of choice but I guess I'm wrong. 我认为在cpp中初始化对象时在()和{}之间进行选择只是一个选择问题,但是我想我错了。 Can someone explain this to me ?
谁可以给我解释一下这个 ?
In the first code snippet, the set<string> words(istream_iterator<string>(ifs), istream_iterator<string>())
line is parsed as a declaration of a function words
that has two parameters: istream_iterator<string> ifs
and an unnamed parameter of type istream_iterator<string>
and returns a set<string>
. 在第一个代码段中,将
set<string> words(istream_iterator<string>(ifs), istream_iterator<string>())
行解析为具有两个参数的函数words
声明: istream_iterator<string> ifs
和一个类型为istream_iterator<string>
未命名参数,并返回set<string>
。 That's why it gives a compilation error. 这就是为什么它会导致编译错误。 The second one cannot be parsed as a function declaration, so it works properly.
第二个不能解析为函数声明,因此它可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.