如何* it ++对输出迭代器有效? [英] How is *it++ valid for output iterators?

查看:255
本文介绍了如何* it ++对输出迭代器有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在示例代码中,我经常看到输出迭代器的代码,例如 * it ++ 。表达式 * it ++ 创建 it 的副本,增加 it ,然后返回最终取消引用的副本。根据我的理解,制作一个输出迭代器的副本使源无效。但是,在创建副本后执行的 it 的增量将是非法的,对吗?我的理解输出迭代器是否有缺陷?

解决方案
此表达式只是为了方便起见,语义。只有 operator = 才能执行实际作业。例如,在 ostream_iterator 运算符* 运算符++ 运算符++(int)只执行一个的东西: return * this 换句话说,没有什么!)。我们可以写例如:

  it = 1; 
it = 2;
* it = 3;
++ it = 4;

而不是: * it ++ = 1; * it ++ = 2; * it ++ = 3; * it ++ = 4;


In example code, I often see code such as *it++ for output iterators. The expression *it++ makes a copy of it, increments it, and then returns the copy which is finally dereferenced. As I understand it, making a copy of an output iterator invalidates the source. But then the increment of it that is performed after creating the copy would be illegal, right? Is my understanding of output iterators flawed?

解决方案

The expression *it++ does not (have to) make a copy of it, does not increment it, etc. This expression is valid only for convenience, as it follows the usual semantics. Only operator= does the actual job. For example, in g++ implementation of ostream_iterator, operator*, operator++ and operator++(int) do only one thing: return *this (in other words, nothing!). We could write for example:

it = 1;
it = 2;
*it = 3;
++it = 4;

Instead of: *it++ = 1; *it++ = 2; *it++ = 3; *it++ = 4;

这篇关于如何* it ++对输出迭代器有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆