473,966 Members | 24,146 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Implementing custom iterators

Hi,

I've written a simple sorted linked list class that I'm trying to
implement an iterator for. I'm trying to make the interface to the
iterator simmilar to the STL's iterator interface, so one could do:

SortedList<int> sl;
SortedList<int> ::iterator i;

for (i = sl.begin() ; i != sl.end() ; ++) { /* ... */ }

Right now I'm kind of stuck with the following code:

template <typename T>
class SortedList
{
private:
// To make life easier, our sorted list will be doubly-linked
struct ListNode {
ListNode *next;
ListNode *prev;

T data;

ListNode() { next = prev = NULL; }
} *head, *tail;

int size;

protected:
ListNode* _find(const T&) const;

public:
SortedList(); // Default constructor
SortedList(cons t SortedList&); // Copy constructor
virtual ~SortedList(); // Destructor

// ... Other methods (insert(), remove(), etc...

class _SortedListIter ator {
private:
ListNode *cur; // Current element in list
public:
_SortedListIter ator() : cur(NULL) { }
_SortedListIter ator(ListNode *pos) : cur(pos) { }
T& operator*();
void operator++(); // Prefix
void operator++(int) ;// Postfix

friend bool operator==(_Sor tedListIterator &, _SortedListIter ator&);
friend bool operator!=(_Sor tedListIterator &, _SortedListIter ator&);
};

typedef _SortedListIter ator iterator;

iterator begin() { iterator iter(head); return iter; }
iterator end() {iterator iter(NULL); return iter; }
};

Now, of course this dosen't even compile, but hopefully it kind of
illustrates what I'm trying to do. I'm not entierly certian if I should
declare _SotredListIter ator as a template class, or if I did so, how it
would effect the _SortedListIter ator typedef (AFAIK, typedef's cannot be
used with template typenames). Also, would I have establish friendship
between SortedList and _SortedListIter ator so _SortedListIter ator could
access SortedLists private members?

Thanks,

Chris Schadl
Jul 22 '05 #1
4 8716

"Chris Schadl" <cs*****@satan. blah.org.uk> wrote in message
news:pa******** *************** *****@satan.bla h.org.uk...
Hi,

I've written a simple sorted linked list class that I'm trying to
implement an iterator for. I'm trying to make the interface to the
iterator simmilar to the STL's iterator interface, so one could do:

SortedList<int> sl;
SortedList<int> ::iterator i;

for (i = sl.begin() ; i != sl.end() ; ++) { /* ... */ }

Right now I'm kind of stuck with the following code:

template <typename T>
class SortedList
{
private:
// To make life easier, our sorted list will be doubly-linked
struct ListNode {
ListNode *next;
ListNode *prev;

T data;

ListNode() { next = prev = NULL; }
} *head, *tail;

int size;

protected:
ListNode* _find(const T&) const;

public:
SortedList(); // Default constructor
SortedList(cons t SortedList&); // Copy constructor
virtual ~SortedList(); // Destructor

// ... Other methods (insert(), remove(), etc...

class _SortedListIter ator {
private:
ListNode *cur; // Current element in list
public:
_SortedListIter ator() : cur(NULL) { }
_SortedListIter ator(ListNode *pos) : cur(pos) { }
T& operator*();
void operator++(); // Prefix
void operator++(int) ;// Postfix

friend bool operator==(_Sor tedListIterator &, _SortedListIter ator&); friend bool operator!=(_Sor tedListIterator &, _SortedListIter ator&); };

typedef _SortedListIter ator iterator;

iterator begin() { iterator iter(head); return iter; }
iterator end() {iterator iter(NULL); return iter; }
};

Now, of course this dosen't even compile,
try
friend bool operator==(cons t _SortedListIter ator&, const
_SortedListIter ator&);
friend bool operator!=(cons t _SortedListIter ator&, const
_SortedListIter ator&);

It should compile (it worked to me) and besides, this is what you mean, I
guess. If you are only comparing two objects, you don't mean to change any
of them. I don't understand why you are making these operators friends,
since you are declaring them iside the class SortedList. You might as well
declare them like this:

bool operator==(cons t _SortedListIter ator&) const;
bool operator!=(cons t _SortedListIter ator&) const;

I'm not entierly certian if I should declare _SotredListIter ator as a template class, or if I did so, how it would effect the _SortedListIter ator typedef
I am sorry, I don't know the answer for this one. I will leave it to
someone else to answer. But I think that if you are not using a type other
than T in _SotredListIter ator there is no reason to declare it as a
template. Unless, of course, you declare _SotredListIter ator out of
SortedList, which for some reason (I don't know why) is more common.

(AFAIK, typedef's cannot be used with template typenames).
You mean something like this ? :

_SortedListIter ator<T> iterator;

Why not?
Also, would I have establish friendship between SortedList and _SortedListIter ator so _SortedListIter ator could access SortedLists private members?


Again, it depens on wether _SotredListIter ator belongs or not to SortedList.
If not, you should need to declare it as a friend so that it can access cur.

I am sorry for not having any strait and clear answer to your questions. I
only gave my opinion. I hope someone else can clarify this for us.

Regards

Adriano

Jul 22 '05 #2
On Wed, 05 May 2004 09:42:18 +0900, Adriano Dal Bosco wrote:

"Chris Schadl" <cs*****@satan. blah.org.uk> wrote in message
news:pa******** *************** *****@satan.bla h.org.uk...
Hi,

I've written a simple sorted linked list class that I'm trying to
implement an iterator for. I'm trying to make the interface to the
iterator simmilar to the STL's iterator interface, so one could do:
<snip>
Now, of course this dosen't even compile,


try
friend bool operator==(cons t _SortedListIter ator&, const
_SortedListIter ator&);
friend bool operator!=(cons t _SortedListIter ator&, const
_SortedListIter ator&);

It should compile (it worked to me) and besides, this is what you mean, I
guess. If you are only comparing two objects, you don't mean to change any
of them. I don't understand why you are making these operators friends,
since you are declaring them iside the class SortedList. You might as well
declare them like this:


Yup, you're right. I forgot to declare the arguments as const, and I
don't know what the hell I was smoking when I decided to make them friend
functions. Once I fixed that (along with a couple of implementation details)
everything worked fine.

Thanks!

Chris Schadl

Jul 22 '05 #3
Chris Schadl wrote:

I've written a simple sorted linked list class that I'm trying to
implement an iterator for. I'm trying to make the interface to the
iterator simmilar to the STL's iterator interface, so one could do: SortedList<int> sl;
SortedList<int> ::iterator i; for (i = sl.begin() ; i != sl.end() ; ++) { /* ... */ } [snip]

Though you may be able to use a _SortedListIter ator in some limited
ways (e.g. as above), it does not yet integrate into the framework of
the standard library.
For example, the algorithms from the standard library (or any algorithms
that follow the STL conventions) may not (many will likely not) work
with _SortedListIter ator.

There are certain requirements that an iterator class must satisfy in
order to be "compliant" . First, an iterator needs to define several types
(the essential ones are value_type, difference_type and iterator_catego ry).
Then it must lend itself to be used in certain expressions, the exact list
of which varies according to the category defined by iterator_catego ry
(although your class seems to be fine as a forward iterator).

Luckily, there is a class template std::iterator<> . If you derive
from it properly you will get all the necessary typedefs.

iterator end() {iterator iter(NULL); return iter; }
I don't think the above will work (the end() is supposed to be something
you arrive at by incrementing an iterator pointing to the last valid element).

Now, of course this dosen't even compile, but hopefully it kind of
illustrates what I'm trying to do. I'm not entierly certian if I should
declare _SotredListIter ator as a template class, or if I did so, how it
would effect the _SortedListIter ator typedef (AFAIK, typedef's cannot be
used with template typenames).
I'm not sure I understand; if what you meant were typedef templates,
then they are presently not allowed. (typedef-name (what is being defined)
can of course be a dependent name, the associated (defining) type can, in
addition, be a template).

Also, would I have establish friendship
between SortedList and _SortedListIter ator so _SortedListIter ator could
access SortedLists private members?

Strictly speaking, SortedList has to declare _SortedListIter ator a
friend if _SortedListIter ator wants to access SortedList's private parts.
[OT] There is a C++ Language Defect Report #45 that says that inner classes
should have friend privileges in respect to the containing class. Many
compilers support this rule already; I happily abuse this fact. Hopefully
the rule will make into the next revision of the standard [/OT].

Nitpicking:
I would make _SortedListIter ator(ListNode *pos) : cur(pos) { }
private (it is of no relevance to the user) and declare SortedList a friend
of _SortedListIter ator.

Denis
Jul 22 '05 #4
Denis Remezov <RE************ *********@yahoo .removethis.ca> wrote in message news:<40******* ********@yahoo. removethis.ca>. ..
[OT] There is a C++ Language Defect Report #45 that says that inner classes
should have friend privileges in respect to the containing class. Many
compilers support this rule already; I happily abuse this fact. Hopefully
the rule will make into the next revision of the standard [/OT].


It's in the working paper for C++0x.

Regards
Michiel Salters
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1753
by: adeleinandjeremy | last post by:
I am taking a second programming course in Java and am currently attempting to apply what I have learned using Python instead. One thing that is puzzling me is how to use an iterator. I am writing a module containing everything I'd need for canonical linked lists. One particularly useful feature would be to use a for loop over the whole structure. For this I have learned the benefits of iterators. I have read a few book entries on Python...
3
5641
by: Adelein and Jeremy | last post by:
I am taking a second programming course in Java and am currently attempting to apply what I have learned using Python instead. One thing that is puzzling me is how to use an iterator. I am writing a module containing everything I'd need for canonical linked lists. One particularly useful feature would be to use a for loop over the whole structure. For this I have learned the benefits of iterators. I have read a few book entries on...
0
1957
by: nick | last post by:
Hi, I need to manage a "layered" collection of objects, where each layer grows independently, e.g, o--+--+--+--+--+ 1st layer | o 2nd layer (empty) | o--+--+--+ 3rd layer |
13
4963
by: Grahamo | last post by:
Hi, I'm implementing a custom iterator (random access type ) so I can use stl algorithms such as sort on my legacy containers. I'm having problems compiling however. when implementing my customIterator class I have defined the operators below (as well as others but they're not important right now, I don't think). class customIterator {
8
2464
by: Mateusz Łoskot | last post by:
Hi, I know iterator categories as presented by many authors: Stroustrup, Josuttis and Koenig&Moo: Input <---| |<--- Forward <--- Bidirectional <--- Random Output <---|
1
6463
by: flopbucket | last post by:
Hi, For the learning experience, I am building a replacement for std::map. I built a templated red-black tree, etc., and all the basic stuff is working well. I implemented basic iterators and operator++, etc., and begin(), end(), and it works as a drop in for std::map if you stick to the methods I have implemented. Anyway, I decided to go and add const_iterator support, thinking that it would be simple, but I ran into a confusing...
3
8927
by: Senthil | last post by:
Hi , I am learning C# and now am stuck with a simple prorgam.Tried googling but didn't get an answer :(. The following program gives me three compilation errors.Can anyone enlighten me? Thanks. using System; using System.Collections.Generic; using System.Text; namespace Collections
5
9386
by: Shikari Shambu | last post by:
Hi, I am trying to implement a collection that implements IEnumerable<T>. I keep getting the following error 'IEnumerator<...>.Current' in explicit interface declaration is not a member of interface. Please help me resolve the error I was able to implement the non Generics version
7
3856
by: Max Odendahl | last post by:
Hi, my own declared class has a stl::list as a member variable. I now need access to those from the outside. Is a custom iterator for my class the best solution for this and how to do this? I would like to sort the list according to different criteria before, so I would like to offer different iterators, which then sort first based on the type of iterator constructed. Any code sample or link would be nice.
11
2432
by: Diego Martins | last post by:
for me, these items are in the 'tricky zone' of C++ does anyone know good material with that? (dealing with subtle details, pitfalls, good practices...) anything like the Effective series from Meyers would be fine ;) thanks! Diego
0
10130
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11780
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10047
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7567
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6367
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6506
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
5107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4694
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.