我正在尝试在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>{} };
我曾认为在C++中初始化对象时选择使用()还是{}只是个人喜好,但我现在意识到我是错的。有人可以向我解释一下吗?
set<string> words( istream_iterator<string>{ ifs }, istream_iterator<string>{} );
就足够了。 - Slava