std::sort
deduces the Compare
type and accepts it by-value:
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
In most cases it means accepting the comparer by-value.
But that doesn't matter because
- The comparer is usually an empty object with just a
operator()
, so passing it is practically a no-op;
- The compiler can optimize away temporary object creation entirely;
- Even if it isn't empty, copying one object once is negligible in relation to the sorting operation that will follow
In your case struct name_compare
has no members, and so is an empty object.
It is possible to force deduction of the comparer type as a reference by wrapping it in std::ref
.
By the way, a comparer doesn't have to be a class, it can be a static
or a friend
function, too:
struct Record {
string name;
static bool compare(const Record& a, const Record& b) {
return a.name < b.name;
}
void f(vector<Record>& vs) {
sort(vs.begin(), vs.end(), Record::compare);
}
};
But better yet, you can rely on the built-in std::less
implementation and simply define operator<
for your type:
struct Record {
string name;
bool operator< (const Record& that) const {
return name < that.name;
}
void f(vector<Record>& vs) {
sort(vs.begin(), vs.end()); // operator < is used automatically
}
};