arjacsoh
arjacsoh

Reputation: 9232

C++ iterate through a template Map

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?

Upvotes: 4

Views: 5322

Answers (3)

AmokHuginnsson
AmokHuginnsson

Reputation: 1214

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 ) {
     ...
}

Upvotes: 1

hmjd
hmjd

Reputation: 121961

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?

Upvotes: 4

Constantinius
Constantinius

Reputation: 35039

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
}

Upvotes: 0

Related Questions