M
mathieu
Hi there,
I am currently stuck on the following simple problem: implementing
an iterator for a class using the Composite Pattern. I feel like I
have to reimplement a complete new class for iterating over the
Element, since I cannot use directly the std::vector<>::iterator. Did
I miss anything, can I reuse something from the STL ?
Thanks
-Mathieu
class Element
{
public:
Element():key(-1) {}
virtual ~Element() {}
int getkey() const { return key; }
void setkey(int k) { key = k; }
private:
int key;
};
class CompositeElement : public Element
{
public:
CompositeElement():Elements() { }
typedef std::vector<Element*>::iterator iterator;
iterator begin() { return Elements.begin(); }
iterator end() { return Elements.end(); }
void push_back(Element * el)
{
Elements.push_back(el);
}
private:
std::vector<Element*> Elements;
};
int main()
{
CompositeElement root;
// fill root ...
for (CompositeElement::iterator it = root.begin(); it != root.end();
it++)
{
Element* el = *it;
std::cout << el->getkey() << std::endl;
}
return 0;
}
I am currently stuck on the following simple problem: implementing
an iterator for a class using the Composite Pattern. I feel like I
have to reimplement a complete new class for iterating over the
Element, since I cannot use directly the std::vector<>::iterator. Did
I miss anything, can I reuse something from the STL ?
Thanks
-Mathieu
class Element
{
public:
Element():key(-1) {}
virtual ~Element() {}
int getkey() const { return key; }
void setkey(int k) { key = k; }
private:
int key;
};
class CompositeElement : public Element
{
public:
CompositeElement():Elements() { }
typedef std::vector<Element*>::iterator iterator;
iterator begin() { return Elements.begin(); }
iterator end() { return Elements.end(); }
void push_back(Element * el)
{
Elements.push_back(el);
}
private:
std::vector<Element*> Elements;
};
int main()
{
CompositeElement root;
// fill root ...
for (CompositeElement::iterator it = root.begin(); it != root.end();
it++)
{
Element* el = *it;
std::cout << el->getkey() << std::endl;
}
return 0;
}