how portable is end iterator decrement?

前端 未结 3 1746
庸人自扰
庸人自扰 2020-11-30 02:43

Just encountered decrement of end() iterator in my company source codes and it looks strange for me. As far as I remember this was working on some platforms, bu

3条回答
  •  半阙折子戏
    2020-11-30 03:28

    from the documentation for std::prev

    Although the expression --c.end() often compiles, it is not guaranteed to do so: c.end() is an rvalue expression, and there is no iterator requirement that specifies that decrement of an rvalue is guaranteed to work. In particular, when iterators are implemented as pointers, --c.end() does not compile, while std::prev(c.end()) does.

    which means the implementation for the prefix decrement operation may not be the inside class form iterator iterator::operator--(int) but overloaded outside class form iterator operator--(iterator&, int).

    so you should either prefer std::prev or do the following: { auto end = a.end(); --end; };

提交回复
热议问题