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

标签 c++ boost-iterators

我有以下类(class):

#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;

最佳答案

如果不强制使用 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替代方案。

关于c++ - 将具有指针值类型的 unordered_map 上的迭代器转换为具有 const 引用值类型的同一映射上的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38557243/

相关文章:

c++ - 将 JsonCPP ValueIterator 与 STL 算法结合使用

c++ - 使用 BOOST_FOREACH 修改 std::vector 中的指针

c++ - 2个范围的所有组合的迭代器

c++ - 自定义容器的自定义迭代器

c++ - 将基于范围的 for 循环与第三方容器结合使用

c++ - 自动存储的析构函数

c++ - 具有 3 个类别的 OpenCV SVM 预测置信度

c++ - 重载解析不适用于运算符重载

c++ - 单例行为相关查询

c++ - 链接基于 Qt 的应用程序时出错