2

My task is to display the first and last elements of the list. I have iterators that point to the first and last element of a list. With their help, I am trying to implement a task. Everything works with the first element, with the last - the program crashes. What could be the problem?

typedef list<float>::iterator it;
it i = X.begin(); it j = X.end();
cout << "First element -->> " << *i << "\tLast element -->> ";
cout << *j << endl;
ForceBru
  • 43,482
  • 10
  • 63
  • 98
dbUser11
  • 305
  • 1
  • 10
  • [iterator end reference](http://www.cplusplus.com/reference/iterator/end/): Returns an iterator pointing to the **past-the-end element** in the sequence: – kaylum Apr 20 '20 at 12:20

2 Answers2

2

According to the docs:

end Returns an iterator pointing to the past-the-end element in the sequence

This element does not exist, so you can't access it. But it allows you to iterate nicely (using < for comparison, not <=):

for (it = X.begin(); it < X.end(); ++it)
    // do stuff
ForceBru
  • 43,482
  • 10
  • 63
  • 98
2

The functions begin() and end() define a half open range([begin, end)), which means: The range includes first element but excludes the last element. Hence, the name past the end.

enter image description here

See this answer for The advantage of an half open range.

Have a look at cppreference. To print the last element, try this:

typedef list<float>::iterator it;
it i = X.begin(); it j = X.end();
cout << "First element -->> " << *i << "\tLast element -->> ";
cout << *(j - 1) << endl;

Or

A better option would be rbegin().

typedef list<float>::iterator it;
it i = X.begin(); it j = X.rbegin();
cout << "First element -->> " << *i << "\tLast element -->> ";
cout << *j << endl;
abhiarora
  • 9,743
  • 5
  • 32
  • 57