【发布时间】:2020-12-10 13:51:23
【问题描述】:
在下面的代码中,迭代器指向的值对于最后一个和倒数第二个元素都是相同的。
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> s1 = {4,3,2,5,1};
set<int>::iterator i;
i = s1.end();
cout << *i << endl; // 5
i--;
cout << *i << endl; // 5
cout << *s1.end() << endl; // 5
cout << *(--s1.end()) << endl; // 5
return 0;
}
在我的理解中,end 元素指向的值应该是 null。 为什么会这样?
【问题讨论】:
-
“在我的理解中,end 元素指向的值应该是 null” - 即使这是真的(事实并非如此),取消引用空指针会调用 未定义的行为
-
目标是
vector,但其实是一样的,关联容器没什么特别的。
标签: c++ c++11 containers