BanjoKaJoey
BanjoKaJoey

Reputation: 1

c++ Iterate through template map

I'm having trouble iterating through an std::map I've constructed for a template Counter class. The class is entirely defined in a file called "Counter.h" because I read you should implement whole template classes in the header file, and I was having problems splitting functionality into a .cpp. The pertinent areas of "Counter.h" go something like...

//File: Counter.h

template class<T> class Counter {
  public:
    void foo() {
      class map<T,size_t>::iterator it;  //PROBLEM IS HERE.
      for (it = counts.begin(); it != counts.end; it++) {
        //Do map stuff.
      }   
    }

  private:
    map<T,size_t> counts;
}

However, the declaration of the iterator throws the following error:

error: elaborated type refers to a typedef
       class map<T,size_t>::iterator mapIt;
                            ^

I'm having trouble wrapping my head around this. Any ideas?

Upvotes: 0

Views: 860

Answers (2)

user2209008
user2209008

Reputation:

Working code with examples:

#include <iostream>
#include <map>

template<typename T>
struct counter_t
{
    void foo()
    {
        for (auto itr = counts.begin(); itr != counts.end(); ++itr)
        {
            std::cout << itr->first << ":" << itr->second << std::endl;
        }
    }

    std::map<T, size_t> counts;
};

int main()
{
    counter_t<int> a;
    a.counts.insert(std::make_pair(0, 42));
    a.counts.insert(std::make_pair(1, 62738));

    counter_t<char> b;
    b.counts.insert(std::make_pair('a', 23051));
    b.counts.insert(std::make_pair('b', 123789));

    a.foo();
    b.foo();
}

Output:

0:42
1:62738
a:23051
b:123789

Upvotes: 0

Qaz
Qaz

Reputation: 61970

Replace class with typename:

typename map<T,size_t>::iterator it;

It's not a class, but a typedef, so using class won't work (it's almost always unnecessary to access a class type like this in C++ anyway). typename is necessary because it's a dependent name.

Apart from that, you have a couple odd ends such as meaning to say template<class T> class Container and it != counts.end().

Upvotes: 1

Related Questions