【问题标题】:Using template iterator in C++ std::map在 C++ std::map 中使用模板迭代器
【发布时间】:2014-05-27 11:01:21
【问题描述】:

目标是使用模板打印地图中的每个 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->first 无法解析,这是什么问题?

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

【问题讨论】:

  • 编译器究竟是怎么说的?
  • 你给我上了一课,谢谢!

标签: c++ templates map iterator


【解决方案1】:

模板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

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2011-10-28
    • 1970-01-01
    • 2019-04-08
    • 2015-03-05
    • 2018-04-27
    相关资源
    最近更新 更多