Why use rbegin() instead of end() - 1?

拈花ヽ惹草 提交于 2019-12-05 01:24:05

rbegin() return an iterator with a reverse operator++; that is, with a reverse_iterator you can iterate through a container going backward.

Example:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> v{0,1,2,3,4};
    for( auto i = v.rbegin(); i != v.rend(); ++i )
        std::cout << *i << '\n';
}

Furthermore, some standard containers like std::forward_list, return forward iterators, so you wouldn't be able to do l.end()-1.

Finally, if you have to pass your iterator to some algorithm like std::for_each that presuppose the use of the operator++, you are forced to use a reverse_iterator.

If the container is empty, end() - 1 will not be defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!