std::sort: The comparison object expected by it has to return true if the first argument is less than (i.e. is ordered before) the second.
strcmp, the function you provided has another return convention:
- Negative value if lhs is less than rhs.
- 0 if lhs is equal to rhs.
- Positive value if lhs is greater than rhs.
(here lhs and rhs reffer to left hand operator and right hand operator)
So you have to create your own wrapper function around strcmp.
If you could use c++11 and if you could use c++ for real (i.e. std::string
and std::vector
) you can use other cool tricks like lambdas.
The classic solution:
bool cmp(char const *lhs, char const *rhs) {
return strcmp(lhs, rhs) < 0;
}
std::sort(tab, tab + n, cmp);
The lambda solution:
std::sort(tab, tab + n, [](char const *lhs,
char const *rhs) { return strcmp(lhs, rhs) < 0; });
The real C++ solution
std::vector<std::string> v = ...;
std::sort(std::begin(v), std::end(b));
solved Using std::sort to sort an array of C strings