//string.h
#include <string>
#include <iostream>
usingnamespace std;
class Lstring {
private :
string s[100];
int count;
public :
Lstring();
Lstring( const Lstring&);
~Lstring();
constchar* operator [] (int i)const ;
int push_back(const string );
void print()const;
//class iterator;
//friend class iterator ;
class iterator {
private :
Lstring &s ;
int index;
public :
//iterator();
iterator(Lstring &);
iterator(Lstring&,bool);
iterator& iterator::operator=(const iterator&);
~iterator();
iterator& operator ++(int );
friend ostream& operator<<(ostream& os, const iterator& it);
};
iterator begin();
iterator end() ;
};
and main function is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//main.cpp
int main()
{
Lstring Lst;
Lst.push_back("Test1");
Lst.push_back("Test2");
Lst.print();
Lstring L2 = Lst;
L2.print();
// Lstring::iterator it
Lstring::iterator it = Lst.begin();
cout << endl << " in the Begin Iterator"<<it<<endl;
it++;
cout << endl << " in the Incrementing Iterator"<<it<<endl;
it = Lst.end();
cout << endl << " in the End Iterator"<<it <<endl;
return 0;
}
i have wrttien this program with refernce to the thinking in cpp volume 1 (chapter Introduction to Templates - page 764) book.
here if want to declare the iterator alone without assiging to the any container(Lstring) class. then how i have to code the zero argument constructor of iterator class.
if pointer are used for references how iterator class implementated to access the container oject.
class IntStack {
enum { ssize = 100 };
int stack[ssize];
int top;
The iterator needs access to these private variables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//
class IntStackIter {
IntStack& s;
int index;
public:
IntStackIter(IntStack& is) : s(is), index(0) {}
intoperator++() { // Prefix
require(index < s.top,//<<=====Iterator class accesses private member of StackInt class
"iterator moved out of range");
return s.stack[++index]; //<<===== and here
}
intoperator++(int) { // Postfix
require(index < s.top, //<<===== and here
"iterator moved out of range");
return s.stack[index++];//<<===== and here
}
};
So the StackInt class declares the IntStackIter iterator class to be a friend - to allow it to access the private members.