tags:

views:

139

answers:

3

I am trying to sort an array of strings, but it's not sorting anything.... what am I doing wrong?

string namesS[MAX_NAMES];

int compare (const void * a, const void * b){
    return ( *(char*)a - *(char*)b );
}


void sortNames(){

    qsort(namesS, MAX_NAMES, sizeof(string), compare);
}
+7  A: 

qsort is inherited from the standard C library. It will not work.

You need to use std::sort for sorting strings.

Specifically, cast std::string to void* and then to char* is undefined and won't work.

Shiroko
" It will not work." It can be made to work. That's not to say it *should* be made to work.
John Dibling
+13  A: 

This is C++, not C. Sorting an array of strings is easy.

#include <string>
#include <vector>
#include <algorithm>

std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());
DeadMG
Note that you can use `std::sort` on an array too (but `std::vector` is a better idea): `std::sort(namesS, namesS+MAX_NAMES);`
Fred Larson
thanks this worked
+1  A: 

algorithm sort in CPP has the same complexity as qsort:

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

bool compare(string a, string b){
    cout << "compare(" << a << "," << b << ")" << endl;
    return (a.compare(b) < 0);
}

int main () {

    string mystrs[] = {"www","ggg","bbb","ssss","aaa"};
    vector<string> myvector (mystrs, mystrs + 5);               
    vector<string>::iterator it;

  sort (myvector.begin(), myvector.end(), compare);

  cout << "vector contains:";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}
LoudNPossiblyRight