4

When I have a template class which contains template map and a const_iterator declared as in the following code by typedef, how can I iterate through the elements of the map outside the class, f.e in main to print them on the output?

template<class K, class V>
class template_map{
private:

    typedef typename std::map<K,V> TMap;
    TMap my_map;

public:
    typedef typename TMap::const_iterator const_iterator;
    ...
};

int main()
{

template_Map<int,double> Map1 //suppose that contains elements

?
}

Update: Can the typedef iterator be used outside the class? If yes in what way?

arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • Your main function is wrong. The complete type would be, for example, `template_map`. Then you can just say `template_map::const_iterator` to name your iterator. You also have to expose the iterator functions of `my_map` in the public interface of `template_map`. – quant_dev Dec 07 '11 at 09:47

3 Answers3

4

You need to define member functions on your template that would return iterators:

template<class K, class V>
class template_map{

private:

typedef typename std::map<K,V> TMap;
TMap my_map;

public:
    typedef typename TMap::const_iterator const_iterator;
    const_iterator begin() const { return my_map.begin(); }
    const_iterator end() const   { return my_map.end(); }
};

Then:

int main()
{
    template_map<int, int> m;
    // Populate map...

    // Then iterate...
    for (auto i = m.begin(); i != m.end(); i++)
    {
    }
}

However, I am unsure what your adding to std::map here, why not just use it as is?

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

Add begin() and end() members to template_Map (both const and non-const variants).

const_iterator begin() const {
    return my_map.begin();
}
const_iterator end() const {
    return my_map.end();
}
iterator begin() {
    return my_map.begin();
}
iterator end() {
    return my_map.end();
}

I added non-const versions just for interface completeness, it may not be required in your case. Than in main:

typedef template_Map<x, y> template_MapXY;
template_MapXY Map1;
...
for ( template_MapXY::const_iterator it( Map1.begin() ), end( Map1.end() ); it != end; ++ it ) {
     ...
}
AmokHuginnsson
  • 1,174
  • 10
  • 14
0

I don't understand why you want to wrap a map class with another one. Why don't you std::map itself?

Iteration over a std::map is usually done like this:

for(std::map<mykey, myvalue>::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
    somevar = it->first; // <<--- points to your key
    someothervar = it->second; // points to your value
}
Constantinius
  • 34,183
  • 8
  • 77
  • 85