使用指针值类型将unordered_map上的迭代器转换为具有const引用值类型的同一映射上的迭代器

时间:2016-07-24 21:59:02

标签: c++ boost-iterators

我有以下课程:

#include <unordered_map>
#include <memory>


class Node {
public:
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    typedef /**???**/ const_iterator;

    const_iterator begin() const;
    const_iterator end() const;

private:
    map_type _children;
};

正如您所看到的,我希望这个类的用户能够迭代_children的元素而无法修改它们。这就是为什么我想创建一个指向类型为pair<char, const Node&>而不是pair<char, ptr_type>的元素的迭代器。

创建一个基础迭代器类对于手头的任务来说似乎有点过于复杂。我已经看过boost迭代器,我认为transform_iterator可能是要走的路,但我还没有找到如何让它工作。

虽然我在这里,有谁知道在哪里可以找到boost-iterators中定义的迭代器的不同示例的示例?每种类型的文档中只有一个示例,它们并不总是符合我的需求(我对这个库很新,我可能错过了一些明显的东西)。

更新:我尝试使用boost::transform_iterator

class Node {
public:
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;


    struct Transformer {
        std::pair<char, const Node&> operator()(const std::pair<char, ptr_type> &p) const {
            return std::pair<char, const Node&>(p.first, *p.second);
        }
    };

    typedef boost::transform_iterator<Transformer, map_type::const_iterator, std::pair<char, const Node&>&, std::pair<char, const Node&>> const_iterator;

    const_iterator begin() const {
        return boost::make_transform_iterator<Transformer, map_type::const_iterator>(_children.begin(), Transformer());
    }
    const_iterator end() const {
        return boost::make_transform_iterator<Transformer, map_type::const_iterator>(_children.end(), Transformer());
    }

private:
    map_type _children;
};

遗憾的是,它没有编译,并给出以下错误:

error: no type named ‘type’ in ‘boost::mpl::eval_if<boost::is_same<boost::iterators::use_default, boost::iterators::use_default>, boost::result_of<const Node::Transformer(const std::pair<const char, std::unique_ptr<Node> >&)>, boost::mpl::identity<boost::iterators::use_default> >::f_ {aka struct boost::result_of<const Node::Transformer(const std::pair<const char, std::unique_ptr<Node> >&)>}’
     typedef typename f_::type type;

2 个答案:

答案 0 :(得分:4)

如果不强制使用boost-iterator,则可以编写自己的迭代器。我发帖一个,满足ForwardIterator。你可以简单地将它扩展到BidirectionalIterator(但它可能有点乏味)。

在发布之前,我恐怕无法满足您的要求(除了使用boost-iterator);使用std::pair<char, const Node*>代替std::pair<char, const Node&>,因为后者禁止复制。也许这就是阻止你编译boost::transform_iterator例子的原因(我不确定;我对boost-iterator不太熟悉)。

无论如何,这是code.cpp(长125行)。 main测试功能包括:

#include <unordered_map>
#include <memory>

class Node;

template <class Map>
class MyIterator {
public:
    // iterator member typedefs
    using iterator_category = std::forward_iterator_tag;
    using value_type = std::pair<char, const Node*>;
    using difference_type = std::ptrdiff_t;
    using pointer = value_type*;
    using reference = value_type&;

    // typedef for underlying iterator
    using underlying_iterator = typename Map::const_iterator;

    // constructors
    // takes an underlying iterator
    explicit MyIterator(underlying_iterator it) : _it(std::move(it)) {}
    // default constructor; required by ForwardIterator
    MyIterator() = default;

    // dereference; required by InputIterator
    reference operator*() {
        update();
        return _p;
    }

    // dereference; required by InputIterator
    pointer operator->() {
        update();
        return &_p;
    }

    // increment; required by Iterator
    MyIterator<Map>& operator++() {
        ++_it;
        return *this;
    }

    // increment; required by InputIterator
    MyIterator<Map> operator++(int) {
        auto mit = *this;
        ++*this;
        return mit;
    }

    // comparison; required by EqualityComparable
    bool operator==(const MyIterator<Map>& mit) const {
        return _it == mit._it;
    }

    // comparison; required by InputIterator
    bool operator!=(const MyIterator<Map>& mit) const {
        return !(*this == mit);
    }

private:
    // this method must be called at dereference-time but not
    // traverse-time in order to prevent UB at a wrong time.
    void update() {
        _p = value_type{_it->first, &*(_it->second)};
    }

    // the underlying iterator that tracks the map
    underlying_iterator _it;
    // the pair of the desired type. without it, e.g. operator-> doesn't
    // work; it has to return a pointer, and the pointed must not be a
    // temporary object.
    value_type _p;
};

class Node {
public:
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    typedef MyIterator<map_type> const_iterator;

    const_iterator begin() const {
        return const_iterator{_children.begin()};
    }
    const_iterator end() const {
        return const_iterator{_children.end()};
    }

private:
    map_type _children;

// additional members for testing purposes.
public:
    Node(std::string name) : _name(std::move(name)) {}
    Node(std::string name, map_type&& children) :
        _children(std::move(children)), _name(std::move(name)) {}
    std::string const& name() const {
        return _name;
    }
private:
    std::string _name;
};

#include <iostream>

// test program; construct a simple tree and print children.
int main() {
    typedef std::unique_ptr<Node> ptr_type;
    typedef std::unordered_map<char, ptr_type> map_type;

    ptr_type leaf1(new Node("leaf1"));
    ptr_type leaf2(new Node("leaf2"));
    ptr_type leaf3(new Node("leaf3"));
    map_type branch;
    branch.emplace('1', std::move(leaf1));
    branch.emplace('2', std::move(leaf2));
    branch.emplace('3', std::move(leaf3));
    Node parent("parent", std::move(branch));

    for (auto it = parent.begin(); it != parent.end(); ++it) {
        std::cout << it->first << ' ' << it->second->name() << '\n';
    }

    return 0;
};

编译命令:

g++ -std=c++11 -g -O2 -Wall code.cpp

我的输出:

3 leaf3
2 leaf2
1 leaf1

MyIterator被编写为模板类,以便在您将std::unordered_map更改为例如std::map,您无需修改​​MyIterator;)

使operator*必须返回对std::pair的引用,使事情变得复杂;这意味着某处必须存在std::pair的(非临时)对象,否则该引用将成为悬空引用。 operator->相同(用“指针”替换“引用”)。

此处MyIterator::_pstd::pair的参考。这是在更新时复制分配的,std::pair<char, const Node&>(包含引用的对)禁止。

std::pair<char, const Node&>的替代方案是std::pair<char, const Node*>std::pair<char, std::reference_wrapper<const Node>>。如果您选择使用it->second->name()替代方法,请将it->second.get().name()替换为std::reference_wrapper

答案 1 :(得分:1)

我认为这可能是boost::indirect_iterator存在的原因。在(普通)map<char, char *>上调整boost文档中的示例:

#include <iostream>
#include <map>
#include <boost/iterator/indirect_iterator.hpp>


int main() {
    char characters[] = "abcdefg";
    size_t ncharacters = sizeof characters - 1;
    char *charptr[ncharacters];

    for (size_t i = 0; i < ncharacters; ++i) {
        charptr[i] = &characters[i];
    }

    std::map <char, char *> map1;
    for (size_t i = 0; i < ncharacters; ++i) {
        map1[characters[i]] = charptr[i]; /* Trivial, just to demonstrate */
    }

    boost::indirect_iterator<char * const*, char const> const_indirect_first(charptr),
                                                        const_indirect_last(charptr + ncharacters);

    std::copy(const_indirect_first, const_indirect_last, std::ostream_iterator<char>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}