dimanche 15 mars 2015

C++ Custom iterator class


I want to implement a custom iterator class that has some differences with typical iterators. The container in this example is a vector and the idea is to walk throw it but using a specific syntax, like this:



int main()
{

VectorElement E;

for (size_t i = 0; i < 5; i++)
{
Element e;
e.id = i;
E.push_back(e);
}

for (ElementIterator e(E); e.end(); ++e)
cout << "Element " << e.id << endl;

}


I tried with the following definitions, but it gives me a Segmentation Fault at the static_cast line after two iterations. Does someone know how to improve this? Thanks



class Element
{
public:

Element() {};
size_t id;
};

typedef vector<Element> VectorElement;

class ElementIterator: public Element
{
typedef vector<Element>::iterator iter;

public:

ElementIterator(const Element& e) : Element(e) { }
ElementIterator(VectorElement& ve_)
{
ve = &ve_;
it = ve->begin();
}

ElementIterator operator++()
{
++it;
*this = static_cast<ElementIterator>(*it);
return *this;
}

bool end()
{
if (it != ve->end() )
return true;
return false;
}

vector<Element>* ve;
iter it;
};



Aucun commentaire:

Enregistrer un commentaire