问题描述
我想使用transform_iterator在范围上进行增量转换.通过增量变换,我的意思是r 应该保持不变,并且后续元素r 映射到(r -r ).
I want to use a transform_iterator to make a delta transformation on a range. By delta transformation I mean that r should stay the same and the subsequent elements, r, are mapped to (r - r).
我的问题是,据我所知,transform_iterator需要一个const函子,但我的函子需要记住先前的值.我该如何解决?我应该只编写自己的迭代器吗?
My problem is that as far as I can tell a transform_iterator needs a const functor, but my functor needs to remember the previous value. How can I solve this? Should I just write my own iterator?
我希望将其用作迭代器的原因是,在下一步中,我想从中制作一个范围适配器.
The reason I want it as an iterator is that in the next step I want to make a range adaptor from it.
似乎transform_iterator确实允许使用非常量函子,并且确实是我的范围适配器抱怨缺少常量性.我将继续公开这个问题,因为关于仍然使用transform_iterator的适当性的讨论似乎很有趣.
It seems transform_iterator does allow non-const functors and that it was really my range adaptor that complained about the lack of constness. I'll keep the question open since the discussion about how appropriate it is to use transform_iterator anyway seems interesting.
推荐答案
我认为您不能通过boost :: transform_iterator完全正确地完成这项工作.这是一个简单的实现,乍看起来似乎可行,但效果并不理想:
I don't think you can have this work completely correctly with boost::transform_iterator. This is a simple implementation that seems like it might work at first, but doesn't really work well:
#include <boost/iterator/transform_iterator.hpp>
#include <vector>
#include <iostream>
using std::cout;
struct Delta {
Delta() : prev_value(0) { }
int operator()(int value) const
{
int result = value-prev_value;
prev_value = value;
return result;
}
mutable int prev_value;
};
int main(int,char**)
{
typedef std::vector<int> Items;
typedef boost::transform_iterator<Delta,Items::iterator,int> Iter;
Items items;
items.push_back(4);
items.push_back(3);
items.push_back(8);
{ // prints 4 -1 5 -- excellent
Iter i(items.begin(),Delta()), end(items.end(),Delta());
for (;i!=end;++i) {
cout << *i << " ";
}
cout << "\n";
}
{ // prints 4 0 -- crap
Iter i(items.begin(),Delta());
cout << *i << " ";
cout << *i << "\n";
}
return 0;
}
要真正实现此目的,您需要知道迭代器何时进行改进,因此我认为您需要自己的迭代器.
To really make this work, you need to know when the iterator is advanced, so I think you'll need your own iterator.
这篇关于将boost :: transform_iterator与非常量函子一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!