Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a vector <char*>?

#include <algorithm>

bool comparisonFunc(char* c1, char* c2)
{
     return strcmp(c1, c2) ? 0 : 1;
}

vector<char*> myVec;
vector<char*>::iterator itr;
sort(myVec.begin(), myVec.end(), comparisonFunc)

Is that correct or is there a better way to do it?

like image 894
user1002288 Avatar asked Dec 28 '22 12:12

user1002288


1 Answers

std::sortexpects a "less than" predicate. You should implement your comparisonFunc() like this:

bool comparisonFunc(const char *c1, const char *c2)
{
    return strcmp(c1, c2) < 0;
}

(Note the consts; they are important.)

Your current implementation couldn't possibly work because you just return if the values are equal or not. That information is not enough to sort - you need to know which one is smaller and which one is bigger (unless, of course, the values are equal).

like image 103
hrnt Avatar answered Dec 30 '22 11:12

hrnt