【发布时间】:2019-06-15 17:19:45
【问题描述】:
我在迭代器中有一个关于begin() 和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 的数字
为什么会有如此不同的结果?
【问题讨论】:
-
rend().base() == begin(). -
rend()返回“past-the-end”迭代器,就像end()一样。取消引用它是未定义的行为。 (好吧,rend()更像是“开始之前”,但你明白了)。 -
rend是结尾的反向迭代器(原始向量的开头),begin 是开头的迭代器 -
v1.begin() <=> --v1.rend()