mercredi 26 décembre 2018

Template container class that uses STL container. How should implement iterator?

I want to write a hierarchy in c++ like in java collections. I have abstract base class so and it's template takes argument an primitve data type and a container type(like vector, list or set). In my base class i have an function that name Iterator() and also i have to write a helper iterator class. How can i implement this helper class? As a inner class or as a seperate class? Can i use template parameter container's iterator in iterator inner class?

This my container base class with full pure function

#ifndef CONTAINER_H
#define CONTAINER_H
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

namespace GeneralContainer{
template <class E, class Alloc = std::vector<E> >
class Collection{
public:
  virtual Alloc::iterator iterator() = 0;//What should i do in here? How can i implement helper iterator class
  virtual bool add(E e) = 0;
  virtual bool addAll(Collection& c) = 0;
  virtual void clear() = 0;
  virtual bool contains(E e) = 0;
  virtual bool containsAll(Collection* c) = 0;
  virtual bool isEmpty() = 0;
  virtual bool remove(E e) = 0;
  virtual bool removeAll(Collection* c) = 0;
  virtual bool retainAll(Collection* c) = 0;
  virtual int size() = 0;
};
}


#endif

This is my iterator implementation.

#ifndef ITER_H
#define ITER_H
#include <iterator>

class MyIterator : public std::iterator<std::input_iterator_tag, class T>
{
  T* p;
public:
  MyIterator(T* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) const {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) const {return p!=rhs.p;}
  T& operator*() {return *p;}
};

#endif

Aucun commentaire:

Enregistrer un commentaire