0

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?

2 Answers2

1

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().

Community
  • 1
  • 1
chris
  • 60,560
  • 13
  • 143
  • 205
0

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
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
  • If using C++11 already, might as well go all-in and do `a.counts = {{0, 42}, {1, 62738}};` and likewise for `b`. The loop could also just be a ranged-for as well given all that's needed inside is the pair. – chris Mar 06 '14 at 02:02
  • From the sounds of it the guy is new to C++, don't want to overwhelm him with too much crazy stuff. But yea, you're right. – Colin Basnett Mar 06 '14 at 02:03