0

I know how to implement a template class.
However, I don't understand how the following list<int>::iterator is implemented internally. Should I make a namespace?
(Basically I want to use the same STL syntax with customized implementation.)

list<int> l;
list<int>::iterator it = l.begin();

In short, what is the simplest way to get the code working without any STL libraries?

Here is a snippet of the custom list implementation: (I omitted most of the methods for readability.)

template <typename T>
struct list {
        struct listNode {
        listNode() : item(0), next(0) {}
                listNode(T x) : item(x), next(0) {}
                T item;
                listNode* next;
        };
        list() : head(0),tail(0) {}     
        listNode* head;
        listNode* tail;
};
9
  • Why not look at your STL implementation and see how list::iterator is implemented? Commented Jul 30, 2017 at 2:10
  • StackOverflow isn't a website to have other people write your code. You need to attempt to write it and if you have problems, post the code that you have and clearly state the specific problem you are having. Commented Jul 30, 2017 at 2:11
  • I guess I did not state my question clearly. I just don't understand the mechanism of the symbol itself. I don't want people to implement my code either. How is it possible for iterator to have an unknown container? Commented Jul 30, 2017 at 2:16
  • What makes you think you need to have an "unknown container"? Commented Jul 30, 2017 at 2:19
  • For example, list<int>::iterator and set<int>::iterator. I wonder how :: symbol works internally. Commented Jul 30, 2017 at 2:20

1 Answer 1

2

You can implement the iterator type inside the container type so that it has any information about the container it is iterating.

template<class T>
class SomeContainer {

public:

    class Iterator {
        // You can use SomeContainer and T in here.  
    };
};
Sign up to request clarification or add additional context in comments.

3 Comments

Note that at least some modern STL implementations do not do this: google SCARY iterators if you care. However, this technique is servicible and is how you should start doing this in order to learn.
This is the answer I was looking for. I didn't know that the nested class is accessible by using :: operator. Thank you.
@PeterHwang added "public:"

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.