473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

A different kind of adaptor iterator

Hi all,

I'm trying to write a special adaptor iterator for my program. I have
*almost* succeeded, though it fails under some circumstances.

See the for-loop in main().

Any pointers/help would be muchly appreciated.

Apologies for the long post - I couldn't find a shorter way to
express my problem without removing too much useful context.

SCoTT. :)

// About this test program:
// I have a single container (std::map) of objects (Object *) as a data
// member of a class (Instrument).
// I provide a set of iterators to access the elements of the container
// in different ways. ie. access elements as Object&, or Object*, or
// const Object&, etc.
// I also allow a function object to be passed to the constructor of the
// iterators. This has the purpose of making the iterator perform
// selective iteration. ie. elements of the container that don't satisfy
// the function object are automatically "skipped".

// What I am trying to achieve:
// 1. Hide the container type from users of the Instrument object.
// 2. Provide various ways to access the elements of the single container.
// 3. Allow iterators to "skip" undesired elements according to a funciton
// object.
// 4. Iterators should be compatible with STL functions.
#include <map>
#include <iostream>
#include <cassert>
#include <ext/algorithm>

using __gnu_cxx::count_if;
using std::cout;
using std::endl;

// The container class stores pointers to Object objects.
class Object
{
public:

int id;
bool bActive;
char objectType;

bool isActive (void)
{
return bActive;
}
};
// Various function objects used to selectively iterate over container objects.
typedef struct FunctionObject
{
virtual bool operator () (Object *p) const
{
(void) p;
return true;
}
};

typedef struct AllObjects : public FunctionObject { };

typedef struct ActiveGuideObjects : public FunctionObject
{
bool operator () (Object *p) const
{
return (p->isActive() && p->objectType == 'A');
}
};

typedef struct ScienceObjects : public FunctionObject
{
bool operator () (Object *p) const
{
return (p->objectType == 'B');
}
};

// The instrument class has the container & adaptor iterator stuff.
class Instrument
{
public:

std::map<int, Object *> m;

// ObjectIteratorBase - the base iterator class. Subclasses inherit
// & provide the "dereference iterator" function. ie. "operator *".
// This class is basically a wrapper around the standard iterators.
class ObjectIteratorBase : public std::iterator_traits<Object *>
{
protected:
std::map<int, Object *>::iterator _it, _end;
const FunctionObject &_fo;

public:
ObjectIteratorBase (
std::map<int, Object *>::iterator it,
std::map<int, Object *>::iterator end,
const FunctionObject &fo) :
_it(it),
_end(end),
_fo(fo)
{
findNext();
}

virtual ~ObjectIteratorBase() {}

// keep incrementing the internal iterator until we
// satisfy the function object.
void findNext (void)
{
while (_it != _end)
{
if (!(_fo(_it->second)))
_it++;
else
break;
}
}

void operator ++ (void)
{
_it++;
findNext();
}

bool operator != (const ObjectIteratorBase &i) const
{
return _it != i._it;
}

bool isValid (void) const
{
return (_it != _end);
}
};

// ObjectIteratorRef - iterator for accessing container objects
// as a reference.
class ObjectIteratorRef : public ObjectIteratorBase
{
public:
ObjectIteratorRef (
std::map<int, Object *>::iterator it,
std::map<int, Object *>::iterator end,
const FunctionObject &fo) :
ObjectIteratorBase(it, end, fo)
{
}

Object &operator * (void)
{
return *(_it->second);
}
};

// Note: <fo> *MUST* be const. (see [dcl.init.ref])
ObjectIteratorRef beginRef (const FunctionObject &fo)
{
return ObjectIteratorRef(m.begin(), m.end(), fo);
}

ObjectIteratorRef endRef (void)
{
return ObjectIteratorRef(m.end(), m.end(), AllObjects());
}

// ObjectIteratorPtr - iterator for accessing container objects
// as a pointer.
class ObjectIteratorPtr : public ObjectIteratorBase
{
public:
static uint counter;
ObjectIteratorPtr (
std::map<int, Object *>::iterator it,
std::map<int, Object *>::iterator end,
const FunctionObject &fo) :
ObjectIteratorBase(it, end, fo)
{
#if 0
cout << "created ObjectIteratorPtr " << counter++ << endl;
cout << "&it=" << &it << " *it=" << it->first << endl;
cout << "&end=" << &end << endl;
cout << "atEnd? is " << (it == end) << endl;
#endif
}

Object *operator * (void)
{
return _it->second;
}
};

ObjectIteratorPtr beginPtr (const FunctionObject &fo)
{
return ObjectIteratorPtr(m.begin(), m.end(), fo);
}

ObjectIteratorPtr endPtr (void)
{
return ObjectIteratorPtr(m.end(), m.end(), AllObjects());
}

// TODO: also need to provide const versions of the iterators.
// ObjectIteratorBase should be made a template class.
};

uint Instrument::ObjectIteratorPtr::counter = 0;

void print (const Object &r)
{
cout << "object " << r.id << " is " << (r.bActive ? "" : "IN")
<< "active and of type: " << r.objectType << endl;
}

typedef struct PrintMe : public std::unary_function<std::pair<const int, Object *>, void>
{
void operator () (std::pair<const int, Object *> &p) const
{
print(*(p.second));
}
};

typedef struct PrintRef : public std::unary_function<Object &, void>
{
void operator () (Object &r) const
{
print(r);
}
};

typedef struct PrintPtr : public std::unary_function<Object *, void>
{
void operator () (Object *p) const
{
print(*p);
}
};
// for_each_if<>:
// Apply an operation to each element of a set that satisfies the
// predicate specified by <pred>.
// Very similar to STL std::for_each template function, but only applies
// the operation <f> on elements that satisfy the predicate <pred>.
template <class InputIterator, class Predicate, class Function>
Function for_each_if (
InputIterator first,
InputIterator last,
Predicate pred,
Function f)
{
for ( ; first != last; ++first)
{
if (pred(*first))
f(*first);
}
return f;
}

int main (void)
{
Instrument instr;
for (uint i = 1; i <= 50; i++)
{
Object *p = new Object();
assert(p != NULL);
p->id = i;
p->bActive = lrand48() % 2;
p->objectType = (char) (65 + lrand48() % 3);
instr.m[i] = p;
}
#if 0
cout << "All objects are:" << endl;
std::for_each(instr.m.begin(), instr.m.end(), PrintMe());
#endif

cout << "Science objects are:" << endl;
std::for_each(instr.beginPtr(ScienceObjects()), instr.endPtr(), PrintPtr());

cout << "Active guide objects are:" << endl;
std::for_each(instr.beginRef(ActiveGuideObjects()) , instr.endRef(), PrintRef());
cout << "Active science objects are:" << endl;
for_each_if(instr.beginRef(ScienceObjects()),
instr.endRef(),
std::mem_fun_ref(&Object::isActive),
PrintRef());

uint n = count_if(instr.beginRef(ScienceObjects()),
instr.endRef(),
std::mem_fun_ref(&Object::isActive));

cout << "There are " << n << " active science objects." << endl;

for (Instrument::ObjectIteratorPtr it = instr.beginPtr(AllObjects());
#if 1
it.isValid(); // this works.
#else
it != instr.endPtr(); // this doesn't! :(
#endif
++it)
{
Object *pObject = *it;
cout << ' ' << pObject->id;
#if 0
// A nested for-loop fails too - even if the outer loop termination
// condition is: it.isValid().
for (Instrument::ObjectIteratorPtr it2(instr.beginPtr(AllObjects()));
it2.isValid();
++it2)
{
cout << "*";
}
cout << endl;
#endif
}
cout << endl;

return 0;
}
Jul 22 '05 #1
4 2487
>// The container class stores pointers to Object objects.
class Object // Poor name choice, BTW...{
int id;
bool bActive;
char objectType; public:
const char objectType; bool isActive (void) bool isActive (void) const {
return bActive;
}
};


So, what exactly IS the problem, so one knows what to look for?

Jul 22 '05 #2
class Object // Poor name choice, BTW...

// About this test program: ^^^^^^^^^^^^

I originally had named this class "Spine", but I didn't want to
confuse readers & have them wonder what the hell a Spine was
so I changed it to Object. Perhaps I was trying to make things
too simple?
So, what exactly IS the problem, so one knows what to look for?

See the for-loop in main(). ^^^^^^^^^^^^^^^^^^^^^^^^^^
#if 1
it.isValid(); // this works.
#else
it != instr.endPtr(); // this doesn't! :(
#endif


If I use the "it != instr.endPtr()" syntax, the for-loop
aborts after iterating over only 1 object. If I use the
"it.isValid()" syntax, it iterates over all of them (good)
but the nested for-loop still won't work.

Apologies if my initial post wasn't clear, I thought it was
intuitive but it's difficult to be objective about one's
own posts.

SCoTT. :)
Jul 22 '05 #3
>I originally had named this class "Spine", but I didn't want to
confuse readers & have them wonder what the hell a Spine was
so I changed it to Object. Perhaps I was trying to make things
too simple?
I wouldnd care if you named it A or foo, or base;
but NOT "object", or "member" or "vector", you know what I mean?
It's like I have to remind myself of what I mean when I think "this
pointer points to and object of a class derived from object..."
So, what exactly IS the problem, so one knows what to look for?

See the for-loop in main(). ^^^^^^^^^^^^^^^^^^^^^^^^^^
#if 1
it.isValid(); // this works.
#else
it != instr.endPtr(); // this doesn't! :(
#endif


If I use the "it != instr.endPtr()" syntax, the for-loop
aborts after iterating over only 1 object. If I use the
"it.isValid()" syntax, it iterates over all of them (good)
but the nested for-loop still won't work.

Apologies if my initial post wasn't clear, I thought it was
intuitive but it's difficult to be objective about one's
own posts.

SCoTT. :)


It's waay too big.

If you have an iteration problem, can you show this with two or three
classes, like

class my_base
{
};

class derived1 : my_base
{
void ouch() const; ///problem here!
................
etc....

And may be just re-post it as new thread.

Jul 22 '05 #4

For anyone who might be following this thread, I located the
source of my problem - a compiler bug.

With g++-3.2.2 the function object is only invoked ONCE! With
g++-3.3.2 it is invoked on every iteration of the loop (as
expected).
void findNext (void)
{
while (_it != _end)
{
if (!(_fo(_it->second)))
_it++;
else
break;
}
}


SCoTT. :)
Jul 22 '05 #5

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

Similar topics

3
by: Stanislaw Salik | last post by:
Hi, Lets suppose we want to use generic algotithms on collections of pointers (both raw and smart). For example, we want to sort a vector of (smart)pointers. We need a comparator that will take...
3
by: Matthias Kaeppler | last post by:
Hello, I need to sort a range of pointers with a predicate which applies to the pointees. I tried to use boost::indirect_iterator, however, this will sort the container with the pointees instead...
15
by: Matthias Kaeppler | last post by:
Hi, as a result of my last posting about an adaption class template for invoking algorithms on a container of iterators or pointers to elements in another container, I have come up with this...
0
by: Tony Johansson | last post by:
Hello!! This is about the adaptor design pattern. If you use the class adaptor its easy to override. It says an object adaptor makes it harder to override Adaptee behavior. It will require...
13
by: Dan Tsafrir | last post by:
is the following code standard? (cleanly compiles under g++-4.0.2): struct Asc { bool operator()(int a, int b) {return a < b;} }; struct Des { bool operator()(int a, int b) {return b > a;} };...
1
by: | last post by:
Greetings All, I'm trying to access a excel file using the odbc data adaptor but the tables arent showing up. I can get connected to the excel file using the Wizard but when I go to do the odbc...
3
by: PengYu.UT | last post by:
Suppose I want a ring_iterator, which is almost like the vector::iterator. But it will equals begin(), when it passed the end(). It is easy to write an adaptor for it. But I'm wondering if there is...
3
by: Diego Martins | last post by:
Let's say I have a vector of pointers of Base vector<Base *vec; Now, someone assured me all elements of the vector are of dynamic type Derived *. I want to use for_each or other STL...
13
by: toton | last post by:
Hi, I have some enum (enumeration ) defined in some namespace, not inside class. How to use the enum constant's in some other namespace without using the whole namespace. To say in little...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...

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.