键/值C ++中迭代器的功能 [英] Keys / Values Functionality to Iterators in C++

查看:123
本文介绍了键/值C ++中迭代器的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经出现在各种各样的猜测之中,但这是有些不同的。

I know this questions has come up in various guises before, but this is slightly different.

我有一个包含std :: map的类。虽然我希望使用地图作为其他目的,在外部我想要暴露一个迭代器适配器只是地图中的值(即std :: pair中的第二个项目)。

I have a class which contains a std::map. Although I wish to use the map for other purposes inside the class, externally I want to expose an iterator adapter to just the values inside the map (ie the second item in the std::pair).

例如在python中,我可能会这样做:

For example in python I might do something like this:

def __iter__(self):
    return self._dict.itervalues()

如何在c ++中执行此操作,隐藏在课堂上实现?

How do I go about doing this in c++, hiding the implementation inside the class?

谢谢,

Dan

推荐答案

看看Boost的 transform_iterator ,它提供了这种功能:

Have a look at Boost's transform_iterator which provides exactly this kind of functionality:

template <typename K, typename V>
struct get_value {
    const V& operator ()(std::pair<K, V> const& p) { return p.second; }
};

class your_class {
    typedef map<int, float> TMap;
    TMap mymap;

public:
    typedef get_value<TMap::key_type, TMap::data_type> F;
    typedef
        boost::transform_iterator<F, TMap::iterator>
        value_iterator;

    value_iterator begin() { return make_transform_iterator(mymap.begin(), F()); }

    value_iterator end() { return make_transform_iterator(mymap.end(), F()); }

    // TODO Same for const versions.
    // Rest of the interface …
};

现在,您可以迭代值,例如像这样:

Now you can iterate over the values, e.g. like this:

your_class c;
// Fill c with some values …
copy(c.begin(), c.end(), ostream_iterator<float>(cout, " "));

这篇关于键/值C ++中迭代器的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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