标准库地图和模板功能

std library map and template functions

本文关键字:功能 地图 标准      更新时间:2023-10-16

我真的不明白为什么这段代码

#include <map>
template<typename T, typename U> std::ostream& operator<<(std::ostream& o,
        const std::map<T,U>& input)
{
    for (std::map<typename T,typename U>::iterator it=input.begin(); it!=input.end(); ++it)
    {
        o << it->first << " => " << it->second << 'n';
    }
    return o;
}

返回此编译错误:

error: wrong number of template arguments (1, should be 4)
error: provided for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’

谁能帮我??

你应该在迭代器声明之前写 typename,并使用const_iterator:

for (typename std::map<T,U>::const_iterator it=input.begin(); it!=input.end(); ++it

运算符<<的参数需要 const 对象。因此,地图的元素必须是恒定的。要实现这一点,请使用const_iterator。迭代器声明中的类型名是必需的,以指示以下表达式是嵌套模板类,具体取决于类型 T 和 U。

另请参阅此问题:理解函数模板的参数