【发布时间】: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