I’m creating a string class(project school) and I down to the last create iterators for it, so my problem is I don’t know where to start I supposed that the begin and the end but how are those implemented. here is the code so far:
class StringsTest {
public:
std::tr1::shared_ptr<char* > word;
char* data;
int size;
int final;
int itSize;
StringsTest();
StringsTest(const StringsTest& orig);
virtual ~StringsTest();
StringsTest(char* strings);
StringsTest& swap( StringsTest& str2 );
int push_back(char a);
char pop_back();
int insert(int where, char what);
int erase(int where);
friend void operator<<(std::ostream& Ostr, const StringsTest& st);
friend std::istream& operator>>(std::istream& Istr, StringsTest& st);
char &operator[](int i);
int sizes();
int check();
stringIte& begin();
stringIte& end();
private:
protected:
};
#endif /* STRINGPROJ_H *
//#endif /* STRINGSTEST_H */
class stringIte {
public:
stringIte();
~stringIte();
And the begining:
stringIte& StringsTest::begin() {
try {
} catch (std::exception e) {
std::cout << " an error has ocurred " << e.what() << std::endl;
}
}
stringIte& StringsTest::end() {
try {
} catch (std::exception e) {
std::cout << "nope " << e.what() << std::endl;
}
}
I have this class how do I implement iterator begin(). Thanks.
First off, you don’t want to return the iterators by reference. Return them by value.
An iterator is like a pointer to an element of a collection (to a character in the string, in your case). One way of implementing them would be to just do
typedef char *stringIte;and use raw pointers as your iterators (they provide all the functionality necessary).begin()would then returndataandend()would returndata + size(assumingdatais the pointer to the string data andsizeis its length without the terminatingNUL.A more fancy way could be a simple structure which could e.g. contain a
StringTest*and anint, and return the appropriate character from the string on derefernce.