user1002288 user1002288 - 1 year ago 51
C++ Question

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?

Answer Source

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).