C++ iterator design pattern

I am trying to learn iterators in C++. I don't understand the use of NameCollection::value_type here in Iterator and addNext.
Also in the next function I get an error when I use value_type value=(*m_itr) instead of NameIterator::value_type = (*m_itr). Can anyone explain the two problems?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class Iterator {
 public:
 typedef T value_type;
 virtual bool hasNext() = 0;
 virtual T next() = 0;
};

class NameManager {
 typedef vector<string> NameCollection;
 NameCollection m_names;
 public:
 class NameIterator: public Iterator< NameCollection::value_type > {
        friend class NameManager;
 private:
        NameManager::NameCollection & m_names;
        NameManager::NameCollection::iterator m_itr;
        NameIterator(NameManager::NameCollection & names) : m_names(names), m_itr(m_names.begin()) {}
 public:
        virtual bool hasNext() {
                return m_itr!=m_names.end();
        }
        virtual NameIterator::value_type next(void) {
                NameIterator::value_type value = (*m_itr);
                ++m_itr;
                return value;
        }
 };
 void addName(NameCollection::value_type name){
        m_names.push_back(name);
 }
 NameIterator getNameIterator(void) {
        return NameIterator(m_names);
        }
 };

int main(void) {
        NameManager nameMgr;
        nameMgr.addName("Jobs");
        nameMgr.addName("Bill");
        nameMgr.addName("Larry");

        NameManager::NameIterator nameItr = nameMgr.getNameIterator();

        while(nameItr.hasNext()) {
                cout<<nameItr.next() << endl;
        }
        return 0;
}
I don't understand the use of NameCollection::value_type here in Iterator and addNext.


1
2
 typedef vector<string> NameCollection;
 NameCollection m_names;


std::vector has a value_type data member which is equal to its first template parameter. In this case that would be std::string.

class NameIterator: public Iterator< NameCollection::value_type >

when we create NameIterator class we set its value_type to NameCollection::value_type which is std::string.

So NameIterator::value_type is equal to std::string we use value_type because it allows us to write more generic code.


Also in the next function I get an error when I use value_type value=(*m_itr) instead of NameIterator::value_type = (*m_itr).


That doesn't give me an error so i couldn't say.
Last edited on
Topic archived. No new replies allowed.