3

The goal is to print each k,v pair in a map, using template:

template<typename K, typename V>
typedef std::map<K,V>::const_iterator MapIterator;

template<typename K, typename V>
void PrintMap(const std::map<K,V>& m) {
    for (MapIterator iter = m.begin(); iter != m.end(); iter++) {
        std::cout << "Key: " << iter->first << " "
              << "Values: " << iter->second << std::endl;
    }
}

However, my compiler says that the expression iter->first could not be resolved, what's the problem?

EDIT: I should read compile errors at first, then trying to solve problems by tracing errors. Asking for help without thinking is not a good habit, thanks to @Oli Charlesworth.

error: template declaration of ‘typedef’
error: need ‘typename’ before ‘std::map<T1, T2>::const_iterator’ because ‘std::map<T1, T2>’ is a dependent scope
error: ‘MapIterator’ was not declared in this scope
error: expected ‘;’ before ‘iter’
error: ‘iter’ was not declared in this scope

COMPLEMENTS: The problem has been discussed in great detail in Where and why do I have to put the "template" and "typename" keywords?. According to @RiaD, there is a trivial solution to this problem as a complement.

template<typename K, typename V>
void PrintMap(const std::map<K,V>& m) {
    typedef typename std::map<K,V>::const_iterator MapIterator;
    for (MapIterator iter = m.begin(); iter != m.end(); iter++) {
        std::cout << "Key: " << iter->first << " "
              << "Values: " << iter->second << std::endl;
    }
}
Community
  • 1
  • 1
fishiwhj
  • 779
  • 2
  • 8
  • 21

1 Answers1

4

template typedef should not compile. Either use using directive or typedef inside a class

#include <map>
#include <iostream>
template<typename K, typename V>
using MapIterator = typename std::map<K,V>::const_iterator;

template<typename K, typename V>
void PrintMap(const std::map<K,V>& m) {
    for (MapIterator<K, V> iter = m.begin(); iter != m.end(); iter++) {
        std::cout << "Key: " << iter->first << " "
              << "Values: " << iter->second << std::endl;
    }
}

int main() {
    std::map<int, int> x = {{5, 7}, {8, 2}};
    PrintMap(x);
    return 0;
}

http://ideone.com/xxdKBQ

RiaD
  • 42,649
  • 10
  • 67
  • 110