Why?
Provide a way to access the elements of a container (or aggregate or collection) object sequentially without exposing its underlying representation
Code:
#include <iostream>
using namespace std;
class ListSequence
{
private:
int items[10];
int index;
int sz;
public:
friend class ListSequenceIterator;
ListSequence()
{
index = -1;
sz = 0;
}
void push_back(int in)
{
items[++index] = in;
sz++;
}
int pop_back()
{
sz--;
return items[index--];
}
bool isEmpty()
{
return (sz == 0);
}
int size()
{
return sz;
}
};
class ListSequenceIterator
{
private:
const ListSequence& listSequence;
int index;
public:
ListSequenceIterator(const ListSequence& l): listSequence(l)
{
index = 0;
}
void operator++() // prefix notation
{
index++;
}
bool is_not_the_end()
{
return index != listSequence.sz;
}
int operator*()
{
return listSequence.items[index];
}
};
int main()
{
ListSequence list1;
for (int i = 1; i < 5; i++) {
list1.push_back(i);
}
cout << "list1.size(): " << list1.size() << endl;
list1.pop_back();
list1.push_back(-1);
list1.push_back(-2);
cout << "list1.size(): " << list1.size() << endl;
ListSequenceIterator listSequenceIterator(list1);
cout << "ListSequence content using ListSequenceIterator: " << endl;
for ( ; listSequenceIterator.is_not_the_end(); )
{
cout << *listSequenceIterator << " ";
++listSequenceIterator;
}
cout << endl;
return 0;
}
Sample run:
list1.size(): 4
list1.size(): 5
ListSequence content using ListSequenceIterator: 1 2 3 -1 -2
No comments:
Post a Comment