我正在尝试编写一个迭代器适配器,它应该在每次取消引用时调用成员函数(或访问对象的成员)。以下是此类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
答案 0 :(得分:0)