目前正在看《Accelerated C++》,在第4章的一个例子中,写了一个函数来读取输入流,如下:
istream &read ( istream & in , vector < double >& work )
{
if ( in ) { // why it is needed ?
double x ; // x denotes the grade
work.clear ( ); // why we need it ?
while ( in >> x )
work.push_back ( x );
in.clear ( ); // understandable.
}
return in;
}
int main ( )
{
vector < double > homework;
vector <double> schoolwork;
read ( cin , homework );
read ( cin , schoolwork );
// code for output
}
为什么需要这个:
if ( in ){.....}
因为 while ( in >> x )
也起到同样的作用,因为当输入流中出现错误(例如类型不匹配)时,它将停止接受输入并且流保持错误状态,使用 in.clear()
进一步清除。这样它就可以在 homework
之后用于 vector schoolwork
。
虽然我们有
while ( in >> x )
可以执行相同的操作,但为什么还需要if ( in )
?其次,我对
work.clear( )
非常困惑。为什么我们需要清除 vector 本身,尽管我们是通过引用传递它?
最佳答案
如果流是坏的,保持 vector 不变,而不是清除它。
函数的行为是用输入替换
work
的内容。如果没有clear
,它将追加输入。模糊的函数名称和缺乏文档,除非您阅读代码 - 重命名函数(例如replace
),或者按值返回一个 vector 而不是让调用者创建一个 vector ,否则不清楚哪个是预期的, 将有助于解决这种歧义。
关于c++ - 编程示例中的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168118/