首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++入门5版:流迭代器和Sales_item

C++入门5版:流迭代器和Sales_item
EN

Stack Overflow用户
提问于 2019-09-24 07:55:00
回答 1查看 36关注 0票数 0

在C++ primer 5Ed中,这一章谈到了流迭代器,他给出了这个例子(第512页):

代码语言:javascript
复制
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中做了两次相同的事情

代码语言:javascript
复制
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
}

为什么他不应该优化它,只在一条语句中使用解引用和增量?因此,只有当记录不同时,才会打印出来,无论条件是什么,都会增加和取消引用:

代码语言:javascript
复制
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
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-24 16:10:39

请坚持以书中的例子为例。您没有准确地检查这些语句。

在……里面

代码语言:javascript
复制
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 =

也许你误解了这一点。

别小题大作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58071446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档