0

I'm struggling to understand implementation requirements for the end() function which returns an iterator pointing one past the last element. What does one past last element mean? Isn't it always going to be null? And if it holds no information then how can I get to the final node of BST with O(1) time complexity with the help of end()?

6
  • There's no standard BST container. Did you mean std::set? Commented Mar 17, 2015 at 22:08
  • I'm trying to implement my own container for BST. It's a college assignment. Commented Mar 17, 2015 at 22:14
  • You should have said so from the beginning. Have you looked at any existing implementations so far? Commented Mar 17, 2015 at 22:15
  • I checked few but couldn't understand much, I found them to be really complex, I don't really have that much time to figure out how they function. I am trying to design rather basic and simple solution for the purpose of assignment. Commented Mar 17, 2015 at 22:25
  • I've a pointer to parent along with left and right for nodes in BST. So I somehow need to make the node pointed to by iterator returned by end() function point to the last element in BST. What I get from your answer is that I need to create one more node which is logically not in BST but serves to track the last node of BST. Commented Mar 17, 2015 at 22:34

1 Answer 1

1

The concept of a "null" element etc. is something that simply doesn't figure in the iterator semantics. It's literally meaningless. Iterators aren't raw C pointers.

It's on you to design your iterators such that end()-1 on a non-empty container returns the final node, if the iterator is bidirectional to start with.

For the more general case of a forward iterator, all that you really wish is that some iterator equals end() when it's been incremented one past the last element, or begin() == end() when there are no elements.

This is sometimes done by having end() point to a special node that only exists to facilitate end()'s functionality.

An iterator could store a boolean field indicating whether it's the result of end(), for example. Iterators can hold as much information as you desire. It's an optimization to lower that amount, but an optional one.

Nobody forces you, of course, for begin() and end() to be the only available means of obtaining an iterator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.