In C++ primer 5Ed the chapter talks about stream iterators he gives this example (page 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
}
It works fine but I've noticed that inside the loop it does the same thing twice in 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
}
Why shouldn't he optimized it to only use the de-reference and increment in a single statement? So Only when records are different print and whatever the condition increment and de-reference:
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
}
Is this a good idea or should I stick to the example of the book? Thank you?
Please stick to the example of the book. You did not check the statements exactly.
In
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
}
the statements are different.
Please see: sum +=
and sum =
Maybe you misinterpretetd that.
No big deal.