-3

I'm trying to use std::sort to sort an array of C strings. Here's what I've done:

const char *tab[5];
//then fill up the tab
sort(tab, tab+5);

This doesn't seem to work. I've also tried using sort(tab, tab+5, strcmp), which worked, but when I put it into a function, the array remains unchanged. Sorting function:

void sortfunc (const char *tab[], int n){
    filltab(tab, n); //n is the ammount of strings
    sort(tab, tab+n, strcmp);
}

What's wrong with my code?

0

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

0

I've got it working. Like @bolov and @Svalorzen said, I had to write a bool function that returns true or false, instead of -1, 0, 1, like strcmp() does. Here it is, if anyone needs it in the future:

bool cmp(const char *str1, const char *str2){
    if(strcmp(str1, str2)<0) return true;
    else return false;
}
sort(tab, tab+5, cmp);

Thanks for your help.

1 Comment

whenever you see yourself doing if (condition) return true; else return false; then you can just return the condition itself. So, return condition;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.