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;
    }
}
2
  • What exactly does the compiler say? Commented Apr 13, 2014 at 14:26
  • You have taught me a lesson, thanks! Commented Apr 13, 2014 at 14:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.