如何创建过滤向量的迭代器?
假设我有一个名为 SpotDeal
的向量 spot_deals
,它是一个类:
Suppose I have a vector named spot_deals
of SpotDeal
that is a class:
class SpotDeal
{
public:
int deal_id_; // primary key, and vector is sorted by id
string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
double amount_;
}
假设我需要将 spot_deals
的两个子集传递给函数 foo
进行一些计算.但是,我可以制作副本,这会耗费内存和时间.实际上 foo
只需要交易的迭代器.那么我可以创建 vector
的 2 个迭代器,即 it1
和 it2
并将它们传递给 foo
吗?
Say I need to pass two subset of spot_deals
to a function foo
for some computation. I could make copies, however, that would cost memory and time. Actually foo
only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>
, namely it1
and it2
and pass them to foo
?
spot_deals
的两个子集可以被 ccy_pair_
过滤,例如GBPUSD 和 AUDUSD 的交易,或其他条件.所以我正在寻找一种方法来定义一个由向量??和 lambda 函数定义的迭代器(虽然可以等效地是一个仿函数).
The two subset of spot_deals
could be filtered by ccy_pair_
, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).
有没有办法编写一个辅助函数 make_filtered_iterator
以便我可以有类似下面的东西?
Is there a way to write a helper function make_filtered_iterator
so that I can have something like below?
auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);
推荐答案
答案肯定是是".STL 风格的 C++ 迭代器可以用来做各种技巧.一个常见但基本的方法是为 std::map
创建一个迭代器,在取消引用时只给出键或值.
The answer is certainly "yes." C++ iterators in the STL style can be made to do all sorts of tricks. A common but basic one is making an iterator for std::map
which when dereferenced gives only the key or the value.
在您的特定情况下,一个简单的实现可能是这样的:
In your particular case, a simple implementation might be like this:
template <typename BaseIterator>
struct filtered_iterator : BaseIterator
{
typedef std::function<bool (const value_type&)> filter_type;
filtered_iterator() = default;
filtered_iterator(filter_type filter, BaseIterator base, BaseIterator end = {})
: BaseIterator(base), _end(end), _filter(filter_type) {
while (*this != _end && !_filter(**this)) {
++*this;
}
}
filtered_iterator& operator++() {
do {
BaseIterator::operator++();
} while (*this != _end && !_filter(**this));
}
filtered_iterator operator++(int) {
filtered_iterator copy = *this;
++*this;
return copy;
}
private:
BaseIterator _end;
filter_type _filter;
};
template <typename BaseIterator>
filtered_iterator<BaseIterator> make_filtered_iterator(
typename filtered_iterator<BaseIterator>::filter_type filter,
BaseIterator base, BaseIterator end = {}) {
return {filter, base, end};
}
我为 end
设置了一个默认值,因为通常您可以为此使用默认构造的迭代器.但在某些情况下,您可能只想过滤容器的一个子集,在这种情况下,指定结尾会很容易.
I set a default value for end
because typically you can use a default-constructed iterator for that. But in some cases you might want to filter only a subset of the container, in which case specifying the end makes it easy.
相关文章