在C ++ std :: map中使用模板迭代器

时间:2014-04-13 14:24:59

标签: c++ templates map iterator

目标是使用模板打印地图中的每个k,v对:

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;
    }
}

但是,我的编译器说iter-&gt;表达式首先无法解决,问题是什么?

编辑:我应该首先阅读编译错误,然后尝试通过跟踪错误来解决问题。感谢@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

补充Where and why do I have to put the "template" and "typename" keywords?已经详细讨论了这个问题。根据@ RiaD,作为补充,这个问题有一个简单的解决方案。

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;
    }
}

1 个答案:

答案 0 :(得分:3)

模板typedef不应该编译。在类

中使用using指令或typedef
#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