我正在尝试排序一个字符串数组,但它没有排序任何东西....我做错了什么?
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);
}
Run Code Online (Sandbox Code Playgroud)
Pup*_*ppy 45
这是C++,而不是C.对字符串数组进行排序很容易.
#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());
Run Code Online (Sandbox Code Playgroud)
std::qsort继承自标准C库.不起作用.
您需要std::sort用于排序字符串.
具体来说,转换std::string为void*然后char*是未定义的,将无法工作.
CPP中的算法排序与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;
}
Run Code Online (Sandbox Code Playgroud)