c++ - 标准库映射和模板函数

标签 c++ dictionary

<分区>

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

#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 对象。所以 map 的元素必须是常量。要实现这一点,请使用 const_iterator。 迭代器声明中的类型名需要根据类型 T 和 U 指示以下表达式是嵌套模板类。

另见这个问题: Making sense of arguments to a function template

关于c++ - 标准库映射和模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632966/

相关文章:

c++ - QRegularExpressionMatch内存消耗

c++ - 在 Linux 中使用命名管道的简单客户端/服务器程序

python - 替换 pandas DataFrame 上的循环

python - 如何在 python 中创建一个以随机字母作为键且没有重复项的字典?

Python3函数将列表映射到字典中

c++ - 将数据从 Django 传递到 C++ 应用程序并返回

c++ - 如何创建一个在图标上显示文本的 QPushButton?

c++ - 我可以更改 C++ 中的静态变量初始化顺序吗?

python - 在python中读取/写入字典到csv文件

c# - 使用 TypeConverter 作为字典键,但不使用相同类型的字典值?