indirect_iterator for map <t,shared_ptr <u =“”>&gt; </t,>

时间:2013-03-22 18:15:45

标签: c++ boost c++11 iterator boost-iterators

我正在尝试实现map<T, shared_ptr<U>>的“删除”shared_ptr的迭代器,即取消引用pair<T, U&>。我需要这个来使我的包装器在map上适应基于范围的for循环。

boost::indirect_iterator似乎是为满足这种需求而设计的。我试过这个:

typedef std::map<int, std::shared_ptr<int>> M;
typedef boost::indirect_iterator<M::iterator, std::pair<int, int>> It;

由于indirect_iterator要求:

,这不起作用

表达式* v,其中v是iterator_traits :: value_type的对象,应为有效表达式并可转换为引用。

是否可以使用boost::indirect_iterator执行此任务?如果不是,我可以使用boost::iterator_adaptor吗?

1 个答案:

答案 0 :(得分:2)

感谢@Xeo评论,解决方案是使用Boost.Range。我从VC10获得了什么

#include <boost/range/adaptor/map.hpp>
#include <boost/range/adaptor/indirected.hpp>

#if defined(_MSC_VER) && _MSC_VER <= 1600 // VC10
    template< class T >
    typename std::add_rvalue_reference<T>::type declval();
#endif

class Wrapper
{
private:
    typedef std::map<T, std::shared_ptr<U>> Container;

public:
    typedef decltype(declval<Container&>() | boost::adaptors::map_values | boost::adaptors::indirected) IteratorRange;
    typedef decltype(declval<Container&>() | boost::adaptors::map_values | boost::adaptors::indirected) ConstIteratorRange;
    typedef IteratorRange::iterator Iterator;
    typedef ConstIteratorRange::const_iterator ConstIterator;

    Iterator begin()
    {
        return iteratorRange().begin();
    }

    // by analogy
    ConstIterator begin() const;
    ConstIterator cbegin() const;
    Iterator end();
    ConstIterator end() const;
    ConstIterator cend() const;

private:
    IteratorRange iteratorRange()
    {
        return container | boost::adaptors::map_values | boost::adaptors::indirected;
    }

    ConstIteratorRange iteratorRange() const;

private:
    Container container;
};