gpt4 book ai didi

C++ 入门第 5 版 : Stream iterators and Sales_item

转载 作者:行者123 更新时间:2023-11-30 04:43:43 25 4
gpt4 key购买 nike

在 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
}

这是个好主意还是我应该坚持书中的例子?谢谢?

最佳答案

请坚持书中的例子。您没有准确检查语句。

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 =

也许你误解了。

没什么大不了的。

关于C++ 入门第 5 版 : Stream iterators and Sales_item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com