You can give a predicat to std::sort like
std::vector<MyStruct> ary(SIZE);
std::sort(ary.begin(), ary.end(), [](auto a, auto b){return a.level < b.level;});
First, I encourage you to do not use new, new[], delete, delete[]
in C++ modern.
It is better to use Container and Smart Pointers (I use std::vector
here)
Second, what does mean : [](auto a, auto b){return a.level < b.level;}
.
It is an "object" that is named a lambda. Lambda are a bit like function or something like that. This "function" takes two arguments : a and b, which them type are automatically deduced at compile time (thanks to auto).
The whole function is what we call a predicat. Here, you want to compare only the level part, that's why I am using a.level < b.level
.
Also, you can check the documentation of std::sort
function here :
http://en.cppreference.com/w/cpp/algorithm/sort
As you can see, I am using this one :
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
Compare comp
here is the predicat that I defined by a lambda.
More information about lambda here https://stackoverflow.com/a/7627218/4950448
However if like Michaël Roy suggests, you must use C++98, you can use a "functor" (not sure about the name)
struct CompareStructOperatorLess {
bool operator()(const MyStruct &a, const MyStruct &b) const {
return a.level < b.level;
}
};
...
std::sort(ary.begin(), ary.end(), CompareStructOperatorLess());