1

In the code below, the value that the iterator points to is the same for both the last and the second last element.

#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;
}

In my understanding the value pointed to by the end element should be null. Why is this so?

JCGM
  • 85
  • 7
  • 1
    *"In my understanding the value pointed to by the end element should be null"* - even if that were true (which it is not), dereferencing a null pointer invokes *undefined behavior* – UnholySheep Dec 10 '20 at 13:55
  • The target is for `vector`, but it's the same thing really, there's nothing special about associative containers. – cigien Dec 10 '20 at 14:05

3 Answers3

6

You invoked undefined behavior, std::set::end

Returns an iterator to the element following the last element of the set. This element acts as a placeholder; attempting to access it results in undefined behavior.


Undefined behavior renders the entire program meaningless.

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
1

In my understanding the value pointed to by the end element should be null. Why is this so?

Why your understanding is wrong I cannot tell ;). Snarkyness aside: No. There is no "end element". The end iterator points to one past the last element. You cannot dereference it. If you do you invoke undefined behavior.

The last element in a container is typically refered to as the "back" and many containers have a back() method to access it.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

In my understanding the value pointed to by the end element should be null. Why is this so?

It isn't.

The one-past-the-end iterator doesn't "point" to anything; it's not dereferencable.

C-strings might appear at first to be an exception to this rule, but they're not: they are logically terminated by a NULL character that you can check for, but that NULL is still part of an array of char objects, and you cannot dereference a char* that's the one-past-the-end iterator for that array. Think of a C-string's null terminator as a "this page deliberately left blank"; the page doesn't give you any more story, but it's still a page.

Why is the end() element in Associative container print the same value as the last element?

That's one possible result of a program with undefined behaviour.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35