C++定义map类型的模板迭代器

 

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
}

 

展开阅读全文

没有更多推荐了,返回首页