Can I prevent std :: sort from copying the past comparison object

We use a comparator object to sort the vector:

std::vector<Data> v = .... Comparator c = .... std::sort(v.begin(), v,end(), c); 

However, this makes copies of c during sorting and causes performance problems because Comparator objects store a large map (in which requests are executed when the comparison function is called). I thought I could force the use of links:

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

but copies still happen to this. Is there a way to prevent copying, or do I need to force the comparator to store only pointers to heavy data? (I don't think we can use lambda / closures with our compiler version).

+7
c ++ stl
source share
1 answer

First of all, it should be noted that the standard provides very few guarantees regarding how many copies will be made for function objects. If you need to use full-featured functions, you should use referential semantics (have the state that the functor points to, rather than being held inside).

Thus, the first option is to refactor the functor or package 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 thing you would get if you use std::ref (C ++ 11) directly:

 Comparator cmp(...); sort(v.begin(), v.end(), std::ref(cmp)); 
+8
source share

All Articles