在 C++ 中通过引用传递 std 算法谓词
我正在尝试从 std::list
中删除元素并保留已删除元素的一些统计信息。
为此,我使用列表中的remove_if 函数,并且我有一个谓词。我想使用这个谓词来收集统计数据。这是谓词的代码:
class TestPredicate
{
private:
int limit_;
public:
int sum;
int count;
TestPredicate(int limit) : limit_(limit), sum(0), count(0) {}
bool operator() (int value)
{
if (value >= limit_)
{
sum += value;
++count; // Part where I gather the stats
return true;
}
else
return false;
}
};
这是算法的代码:
std::list < int > container;
container.push_back(11);
TestPredicate pred(10);
container.remove_if(pred)
assert(pred.count == 1);
不幸的是,断言是假的,因为谓词是按值传递的。有没有办法强制它通过引用传递?
I am trying to remove elements from a std::list
and keep some stats of deleted elements.
In order to do so, I use the remove_if function from the list, and I have a predicate. I would like to use this predicate to gather statistics. Here is the code for the predicate:
class TestPredicate
{
private:
int limit_;
public:
int sum;
int count;
TestPredicate(int limit) : limit_(limit), sum(0), count(0) {}
bool operator() (int value)
{
if (value >= limit_)
{
sum += value;
++count; // Part where I gather the stats
return true;
}
else
return false;
}
};
And here is the code for the algo:
std::list < int > container;
container.push_back(11);
TestPredicate pred(10);
container.remove_if(pred)
assert(pred.count == 1);
Unfortunately, the assertion is false because the predicate is passed by value. Is there a way to force it to be passed by reference ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
传递引用包装器,可从
获取:如果您只有 C++98/03,但编译器具有 TR1,则可以使用
> 和std::tr1::ref
如果你对你的谓词做了一个小修改:如果所有其他方法都失败了,那么你可以相对轻松地编写一个手动解决方案:
Pass a reference wrapper, available from
<functional>
:If you only have C++98/03 but your compiler has TR1, you can use
<tr1/functional>
andstd::tr1::ref
if you make a small amendment to your predicate:If all else fails, then you can hack up a manual solution with relative ease:
传递给算法的函子可以在算法内复制不确定的次数,因此不能直接在函子中存储状态。另一方面,您可以通过使用指针或对某些外部状态结构的引用来存储函子外部的状态。
The functors passed to the algorithms can be copied inside the algorithm an indeterminate number of times, so you cannot store state directly in the functor. You can, on the other hand, store the state outside of the functor, by using a pointer or reference to some external state structure.