为什么关联容器中的end()元素打印的值与最后一个元素相同?
在下面的代码中,迭代器指向的值对于最后一个元素和倒数第二个元素是相同的。
#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;
}
根据我的理解,结束元素指向的值应该为空。为什么会这样?
回答
您调用了未定义的行为std::set::end
返回指向集合中最后一个元素之后的元素的迭代器。此元素充当占位符;尝试访问它会导致未定义的行为。
未定义的行为使整个程序毫无意义。