【发布时间】:2015-02-12 17:30:43
【问题描述】:
我正在尝试在 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;
}
这样我得到一个编译错误:
expression must have class type
在我调用 copy() 的那一行
如果我将迭代器的构造更改为以下内容,它将起作用:
set<string> words{ istream_iterator<string>{ ifs }, istream_iterator<string>{} };
我认为在 cpp 中初始化对象时在 () 和 {} 之间进行选择只是一个选择问题,但我想我错了。 谁能给我解释一下?
【问题讨论】:
-
其实
set<string> words( istream_iterator<string>{ ifs }, istream_iterator<string>{} );就够了