向量的迭代器是否已过滤? [英] iterators of a vector filtered?
问题描述
假设我有一个名为 spot_deals
的向量,该向量是 SpotDeal
的一个类
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
只需要交易的迭代器。所以我可以做2个 vecto< SpotDeal>
的迭代器,分别是 it1
和 it2
并将它们传递给 foo
?
Say I need pass two subset of spot_deals
to a function foo
for some computation. I could make copies, however, that would cause memory and time. Acutally foo
only need iterators of deals. So can I make 2 iterators of vecto<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 to a way that could define an iterator defined by a vector and a lambda function (could equivalently be functors 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.
这篇关于向量的迭代器是否已过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!