在使用模板函数来打印map容器时遇到的问题。无法识别迭代器 iterator;
使用C++模板和迭代器时遇到问题 error C2760: 语法错误: 意外的令牌“标识符”,预期的令牌为“;”
原来的错误代码
template<typename T1,typename T2>
void printMap(map<T1, T2>& m)
{
for(map<T1, T2>::iterator it = m.begin();it != m.end();it++)
{
cout <<"first"<< it->first <<"second"<< (*it).second << endl;
}
cout << endl;
}
``
无法识别iterator
查到的解决方案为:
修改后没有解决,后发现原因是编译器无法识别模板中的迭代器类型,于是在迭代器前面加上class,问题解决。新的代码
template<class T1,class T2>
void printMap(map<T1, T2>& m)
{
for(class map<T1, T2>::iterator it = m.begin();it != m.end();it++)
{
cout <<"first"<< it->first <<"second"<< (*it).second << endl;
}
cout << endl;
}