Option 1: Create an external function. This is useful if the struct is part of a bigger library and you can't touch it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <algorithm>
struct a
{
int num1;
int num2;
};
bool acompare(a lhs, a rhs) { return lhs.num1 < rhs.num1; }
int main()
{
a array[1000];
std::sort(array, array+1000, acompare);
}
Option 2: Overload the < operator:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <algorithm>
struct a
{
int num1;
int num2;
booloperator<(const a& rhs) const { num1 < rhs.num1; }
};
int main()
{
a array[1000];
std::sort(array, array+1000, acompare);
}
a functor is an object that can be called like a function, with the function-call operator. All standard algorithms in C++ (sort(), max_element(), find_if(), accumulate(), etc) use them.
A pointer to the non-member function acompare in Stewbond's example is a primitive (because it's stateless) functor.
#include <algorithm>
struct a
{
staticint sort_by;// determines which member to sort by
int num1;
int num2;
booloperator<(const a& rhs) const
{
if( sort_by == 1) return num1 < rhs.num1;// sort by num1
return num2 < rhs.num2;// sort by num2
}
};
int a::sort_by = 1;// default will be to sort by num1
int main()
{
a array[1000];
std::sort(array, array+1000);// sorted by num1
a::sort_by = 2;// changing sort criteria to num2
std::sort(array, array+1000);// sorted by num2
}
I get this error when the 3rd argument array[0] is included in the call to sort():
c:\mingw\bin\..\lib\gcc\mingw32\4.5.2\include\c++\bits\stl_algo.h|2125|error: no match for call to '(a) (a&, a&)'|
Stewbond, are you sure that belongs?
It works great with just std::sort(array, array+1000)
#include <algorithm>
struct A
{
int x, y;
};
int main()
{
A array[1000];
//...
std::sort(array, array+1000, [](A a, A b){ return a.x < b.x; });
std::sort(array, array+1000, [](A a, A b){ return a.y < b.y; });
}