I am trying to write my own iterator (BIter) class to handle my generic bag class. How do I define my .begin and end functions which are found in the bag class definition, not the iterator class?
Code:
template<class item>
class BIter
{
public:
BIter(){}
item& operator*() {return *ptr;}
BIter& operator++(){ptr++; return *this; }
bool operator==(const BIter& b)
{
return ptr==b.ptr;
}
private:
item *ptr;
};
template<class type>//allows more variability than typedef
class bag
{
public:
bag(int init_cap=30);
bag(bag& b); //copy constructor
void insert(type);
void remove(type);
void operator=(bag b);
//Post: The bag has a deep copy of bag b
~bag();//destructor
typedef BIter<type> Iterator;
Iterator begin()
{
type* x=pData;
return x;
}
Iterator end()
{
type* x=pData[used];
return x;
}
private:
int used;//a member to record the number of items in bag
type *pData;//a pointer to point to the dynamic array
int capacity;//a member to record the capacity of a bag
};
template<class type>
bag<type>::bag(int init_cap)
{
used=0;//an empty bag
pData=new type[init_cap];//a dynamic array is created
//and assigned to the pointer pData
capacity=init_cap;
}
template<class type>
void bag<type>::insert(type x)
{
if(used==capacity)
return;
pData[used]=x;
used++;
}
template<class type>
void bag<type>::remove(type t)
{
for(int i=0;i<used;i++)
if(pData[i]==t)
{
pData[i]=pData[used-1];
used--;
return;
}
}
template<class type>
void bag<type>::operator=(bag b)
{
if(capacity!=b.capacity)
return;
for(int i=0;i<b.used;i++)
pData[i]=b.pData[i];
used=b.used;
}
template<class type>
bag<type>::bag(bag& b)
{
capacity=b.capacity;
pData=new type[capacity];
for(int i=0;i<b.used;i++)
pData[i]=b.pData[i];
used=b.used;
}
template<class type>
bag<type>::~bag()
{
delete [] pData;
}