My book asked me to create a simple version of a list that held strings.
Here's what I did.

class String_list{
public:
	typedef std::string* iterator;
	typedef std::string* const_iterator;
	typedef size_t size_type;

	String_list(){
		data = limit = 0;
	};
	String_list(size_type, std::string);

	size_type size() const{return limit - data;};
	bool empty() {return data == limit;};

	iterator begin(){return data;};
	iterator end(){return limit;};
	const_iterator begin() const{return data;};
	const_iterator end() const{return limit;};

	void push_back(std::string);

private:
	iterator data;
	iterator limit;
};

and it asked me to write a bidirectional iterator for it, but I don't know what to do ... cuz the iterators I am using work like random access iterators since they are pointers to string ... (btw I didn't include the definitions of the constructors/push_back cuz they're working just fine)

Every random-access iterator is a bidirectional iterator.

I know that ... but I think what it wants me to do is to adapt this to work with a bidirectional iterator ... cuz a bidirectional iterator is not a random-access iterator ... I think it wants me to do so in order to make it really close to the list class (the next exercise asks me to implement a basic version of the list class) ... so I need to know what to do ... cuz these bidirectional iterators should make it easier to delete/insert elements in the container ... but this would keep them from giving us easy random access like what we have in vectors

If you really want to define a bidirectional iterator that is not a random-access iterator, just do it. Define a class that contains one of your random-access iterators, and then implement just the bidirectional-iterator operations on it. Each operation would be implemented in terms of the corresponding random-access iterator operation.

If you really want to define a bidirectional iterator that is not a random-access iterator, just do it. Define a class that contains one of your random-access iterators, and then implement just the bidirectional-iterator operations on it. Each operation would be implemented in terms of the corresponding random-access iterator operation.

That's what I don't know how to do ... I'm trying to think of a way to define this ... can you tell me how to do this ?

#include <iterator>
#include <string> 

struct String_list
{
    struct iterator : std::iterator< std::bidirectional_iterator_tag, std::string >
    {
        explicit iterator( std::string* p ) : ptr(p) {}

        std::string& operator*() { return *ptr ; }
        // ...
        
        iterator& operator++ () { ++ptr; return *this ; }
        // ...

        // and so on for the other bidirectional iterator operations

        private: std::string* ptr;
    };

    // ....

};

Edited 5 Years Ago by vijayan121: n/a

This article has been dead for over six months. Start a new discussion instead.