C ++通过模板Map进行迭代 [英] C++ iterate through a template Map

查看:221
本文介绍了C ++通过模板Map进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个模板类包含模板映射和 const_iterator 声明如下代码 typedef ,我如何迭代通过地图的外部元素的类,fe在主要打印输出?

When I have a template class which contains template map and a const_iterator declared as in the following code by typedef, how can I iterate through the elements of the map outside the class, f.e in main to print them on the output?

template<class K, class V>
class template_map{
private:

    typedef typename std::map<K,V> TMap;
    TMap my_map;

public:
    typedef typename TMap::const_iterator const_iterator;
    ...
};

int main()
{

template_Map<int,double> Map1 //suppose that contains elements

?
}

更新:typedef迭代器可以在外部使用班上?

Update: Can the typedef iterator be used outside the class? If yes in what way?

推荐答案

您需要在模板上定义会返回迭代器的成员函数:

You need to define member functions on your template that would return iterators:

template<class K, class V>
class template_map{

private:

typedef typename std::map<K,V> TMap;
TMap my_map;

public:
    typedef typename TMap::const_iterator const_iterator;
    const_iterator begin() const { return my_map.begin(); }
    const_iterator end() const   { return my_map.end(); }
};

然后:

int main()
{
    template_map<int, int> m;
    // Populate map...

    // Then iterate...
    for (auto i = m.begin(); i != m.end(); i++)
    {
    }
}

不确定您在 std :: map 中添加的内容,为什么不直接使用它?

However, I am unsure what your adding to std::map here, why not just use it as is?

这篇关于C ++通过模板Map进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆