在cpp中将单词从一个文件复制到另一个文件
Copying words from one file to another in cpp
我试图在 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>())
行被解析为函数 words
的声明,该函数具有两个参数:istream_iterator<string> ifs
和类型为 [=13 的未命名参数=] 和 returns 一个 set<string>
。这就是它给出编译错误的原因。第二个不能被解析为函数声明,因此它可以正常工作。
我试图在 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>())
行被解析为函数 words
的声明,该函数具有两个参数:istream_iterator<string> ifs
和类型为 [=13 的未命名参数=] 和 returns 一个 set<string>
。这就是它给出编译错误的原因。第二个不能被解析为函数声明,因此它可以正常工作。