在C++ primer 5Ed中,这一章谈到了流迭代器,他给出了这个例子(第512页):
int main(){
istream_iterator<Sales_item> item_iter(cin), eof;
ostream_iterator<Sales_item> out_iter(cout, "\n");
// store the first transaction in sum and read the next record
Sales_item sum = *item_iter++;
while (item_iter != eof) {
// if the current transaction (which is stored in item_iter) has the same ISBN
if (item_iter->isbn() == sum.isbn())
sum += *item_iter++; // add it to sum and read the next
transaction
else {
out_iter = sum; // write the current sum
sum = *item_iter++; // read the next transaction
}
}
out_iter = sum; // remember to print the last set of records
}它工作得很好,但我注意到在循环中,它在if-statement中做了两次相同的事情
if (item_iter->isbn() == sum.isbn())
sum += *item_iter++; // add it to sum and read the next transaction
else {
out_iter = sum; // write the current sum
sum = *item_iter++; // read the next transaction
}为什么他不应该优化它,只在一条语句中使用解引用和增量?因此,只有当记录不同时,才会打印出来,无论条件是什么,都会增加和取消引用:
while (item_iter != eof) {
if (item_iter->isbn() != sum.isbn()) // instead of check for equality
out_iter = sum; // write the current sum
sum = *item_iter++; // read the next transaction
}这是一个好主意,还是我应该坚持书中的例子?谢谢?
发布于 2019-09-24 16:10:39
请坚持以书中的例子为例。您没有准确地检查这些语句。
在……里面
if (item_iter->isbn() == sum.isbn())
sum += *item_iter++; // add it to sum and read the next transaction
else {
out_iter = sum; // write the current sum
sum = *item_iter++; // read the next transaction
}这些语句是不同的。
请参阅:sum +=和sum =
也许你误解了这一点。
别小题大作。
https://stackoverflow.com/questions/58071446
复制相似问题