C++定义map类型的模板迭代器
template <typename K, typename V>
using MapIterator_T = typename std::map<K, V>::iterator;
使用下面这种形式会报错
template <typename K, typename V>
typename std::map<K, V>::iterator MapIterator_T; //error
代码示例
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
template <typename K, typename V>
using MapIterator_T = typename std::map<K, V>::iterator;
//typename std::map<K, V>::iterator MapIterator_T; //error
template <typename K, typename V>
void show(map<K, V>& m)
{
cout << "[" << __func__ << "] ";
// auto it = m.begin();
MapIterator_T<K, V> it = m.begin();
for (it = m.begin(); it != m.end();)
{
cout << it->first << ": " << it->second;
it++;
if (it != m.end())
{
cout << ", ";
}
}
cout << endl;
}
void test()
{
map<int, string> mis1; // (1)
show(mis1);
mis1[1] = "good";
mis1[9] = "map";
show(mis1); //1: good, 9: map
}
原文链接:https://blog.csdn.net/halazi100/article/details/88195692

本文介绍了如何在C++中使用模板来定义map类型的迭代器。示例展示了如何通过`using`关键字定义`MapIterator_T`模板别名,并在函数`show`中使用这个迭代器遍历并打印map的内容。错误的定义方式会导致编译错误。
C++定义map类型的模板迭代器(undefined map)&spm=1001.2101.3001.5002&articleId=118495357&d=1&t=3&u=fe23070d01bb4e3cb00a14c189ea522e)
277

被折叠的 条评论
为什么被折叠?



