begin()和rend()有什么区别? [英] What is the difference between begin () and rend ()?

查看:68
本文介绍了begin()和rend()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在迭代器中有一个问题,关于 begin() rend()之间的区别.

I have a question in iterators about the difference between begin() and rend().

#include <iostream>
#include <array>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> v1;
    v1 = {9,2,6,4,5};
    cout<<*v1.begin();
    cout<<*v1.rend();
    return 0;
}

cout<< * v1.begin(); 返回9

但是 cout<< * v1.rend(); 返回不为9的数字

为什么会有如此不同的结果?

Why are there such different results?

推荐答案

在C ++中,范围由一对迭代器标记,这些迭代器标记了范围的开始和位置,该位置在范围的末尾.对于容器, begin() end()成员函数为您提供了一对到首尾位置的迭代器.从 end()读取内容并不安全,因为它没有指向实际元素.

In C++, ranges are marked by a pair of iterators marking the beginning of the range and a position one past the end of the range. For containers, the begin() and end() member functions provide you with a pair of iterators to the first and past-the-end positions. It’s not safe to read from end(), since it doesn’t point to an actual element.

类似地, rbegin() rend()成员函数返回分别指向最后位置和第一个位置的反向迭代器.出于同样的原因,取消引用 end()迭代器是不安全的(超出范围的末尾),因此您不应该取消引用 rend()迭代器,因为它没有指向容器中的元素.

Similarly, the rbegin() and rend() member functions return reverse iterators that point, respectively, to the last and just-before-the-first positions. For the same reason that it’s not safe to dereference the end() iterator (it’s past the end of the range), you shouldn’t dereference the rend() iterator, since it doesn’t point to an element within the container.

这篇关于begin()和rend()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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