我可以阻止std :: sort复制传递的比较对象 [英] Can I prevent std::sort from copying the passed comparison object

查看:126
本文介绍了我可以阻止std :: sort复制传递的比较对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用比较器对象对向量排序:

  std :: vector< Data& v = .... 
比较器c = ....
std :: sort(v.begin(),v,end(),c);但是,这会在排序期间复制c,并导致性能问题,因为Comparator对象存储一个大图(在调用比较函数时进行查找)。
我想我可以强制使用引用:

  const Comparator& ref = c; 
std :: sort(v.begin(),v.end(),ref);

但仍会发生副本。
有一种方法来防止复制,或者我必须使比较器只存储指向重数据的指针吗? (我不认为我们可以使用lambda / closures与我们的编译器版本)。

解决方案

该标准对于对函数对象执行多少副本提供了很少的保证。如果你需要使用状态完整的函数,你应该使用引用语义(具有函数指向的状态,而不是在里面)。

也就是说,第一个选择是重构函数或者包装它:

  struct Wrapper {
Comparator * cmp;
Wrapper(Comparator * cmp):cmp(cmp){}
bool operator()(T const& lhs,T const& rhs)const {
return(* cmp) 1hs,rhs);
}
};
Comparator cmp(...);
Wrapper w(& cmp);
sort(v.begin(),v.end(),w);

这实际上是你使用 std :: ref (C ++ 11)直接:

  Comparator cmp 
sort(v.begin(),v.end(),std :: ref(cmp));


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). 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 ? (I don't think we can use lambda/closures with our compiler version).

解决方案

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:

Comparator cmp(...);
sort(v.begin(), v.end(), std::ref(cmp));

这篇关于我可以阻止std :: sort复制传递的比较对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆