迭代引用时调用成员函数的迭代器适配器

时间:2016-11-29 09:26:50

标签: c++ iterator adapter metaprogramming generic-programming

我正在尝试编写一个迭代器适配器,它应该在每次取消引用时调用成员函数(或访问对象的成员)。以下是此类API的示例:

vector<pair<int,int>> ps = {{1,"a"}, {2,"b"}, {3,"c"}};

// Pairs that represent ranges
auto rf = make_adaptor(ps.begin(), ps.end(), [](const auto& x) {return x.first;}
auto rs = make_adaptor(ps.begin(), ps.end(), [](auto& x) {return x.second;}

应打印出123

for_each(rf.first, rf.second, [](const auto& x){std::cout << x;});

应在second中设置对中的每个ps元素:

for_each(rs.first, rs.second, [](auto& x){ x = "hello";});

我尝试使用iterator方法编写自己的make_adaptor类型,但我似乎无法让它工作:

template <typename Iterator, typename UnaryOp>
struct adaptor {
    using value_type = std::result_of<UnaryOp(typename Iterator::reference)>::type;
    using reference = value_type&;
    using pointer = value_type*;
    using difference_type = typename Iterator::difference_type;
    using iterator_category = typename Iterator::iterator_category;

    adaptor(){};
    adaptor(Iterator it, UnaryOp func) : _it(it), _func(func) {}

    reference operator*() const { return _func(*_it); }
    pointer operator->() const { return &_func(*_it); }

    bool operator==(const adaptor& other) const { return _it == other._it; }
    bool operator!=(const adaptor& other) const { return _it != other._it; }

    adaptor& operator++() {
        ++_it;
        return *this;
    }

    Iterator _it;
    UnaryOp _func;
};



template <typename Iterator, typename UnaryOp>
    auto make_adaptor(Iterator first, Iterator last, UnaryOp func) {
        return std::make_pair(adaptor<Iterator, UnaryOp>(first, func),
                              adaptor<Iterator, UnaryOp>(last, func));
    };

原因如下:我们假设我有一个算法convex_hull可以在points上运行。但是现在我的对象包含points作为成员(struct A { points pos;};)。我想在convex_hull s。

的集合上调用A

1 个答案:

答案 0 :(得分:0)

使用range-v3,您可以执行以下操作:

const std::vector<std::pair<int,const char*>> ps = {{1,"a"}, {2,"b"}, {3,"c"}};

for (const auto s : ps | ranges::view::keys)
{
    std::cout << " " << s;
}

for (const auto s : ps | ranges::view::transform([](const auto& p) { return p.first;} ))
{
    std::cout << " " << s;
}

Demo