[英]Can I prevent std::sort from copying the passed comparison object
We're using a comparator object to sort a vector: 我们使用比较器对象来对矢量进行排序:
std::vector<Data> v = ....
Comparator c = ....
std::sort(v.begin(), v,end(), c);
However, this makes copies of c during the sorting, and is causing performance problems, because Comparator objects store a big map (in which lookups are done when calling the comparison function). 但是,这会在排序过程中生成c的副本,并导致性能问题,因为Comparator对象存储一个大的映射(在调用比较函数时会进行查找)。 I thought I could force the use of references with:
我以为我可以强制使用引用:
const Comparator &ref = c;
std::sort(v.begin(), v.end(), ref);
but copies still happen with this. 但副本仍然会发生。 Is there a way to prevent copies, or do I have to make the Comparator store only pointers to heavy data ?
有没有办法防止复制,或者我是否必须使Comparator只存储指向重数据的指针? (I don't think we can use lambda/closures with our compiler version).
(我认为我们的编译器版本不能使用lambda / closures)。
The first thing to note is that the standard provides very little guarantees as of how many copies will be done for function objects. 首先要注意的是,标准对于为函数对象执行的副本数量提供的保证非常少。 If you need to use state-full functions you should use reference semantics (have the state pointed to by the functor, rather than held inside).
如果你需要使用状态完整函数,你应该使用引用语义(让函子指向状态,而不是保持在里面)。
That being said, the first alternative is to refactor the functor or to wrap it: 话虽这么说,第一个选择是重构仿函数或包装它:
struct Wrapper {
Comparator *cmp;
Wrapper(Comparator *cmp) : cmp(cmp) {}
bool operator()(T const & lhs, T const & rhs) const {
return (*cmp)(lhs,rhs);
}
};
Comparator cmp(...);
Wrapper w(&cmp);
sort(v.begin(), v.end(), w);
This is actually the same you would be getting if you use std::ref
(C++11) directly: 如果您直接使用
std::ref
(C ++ 11),这实际上是相同的:
Comparator cmp(...);
sort(v.begin(), v.end(), std::ref(cmp));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.