C++ Primer 5 版:流迭代器和 Sales_item
C++ Primer 5 Edition: Stream iterators and Sales_item
在 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++ 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 =
也许你误解了。
没什么大不了的。