我正在尝试对字符串数组进行排序,但它没有对任何内容进行排序...我做错了什么?
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);
}
发布于 2010-05-10 22:00:04
这是C++,不是C。对字符串数组进行排序很容易。
#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());
发布于 2010-05-10 21:54:08
std::qsort
继承自标准C库。这是行不通的。
您需要使用std::sort
对字符串进行排序。
具体地说,先将std::string
转换为void*
,然后再转换为char*
,这是未定义的,不会起作用。
发布于 2010-05-26 01:54:40
CPP中的算法sort与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;
}
https://stackoverflow.com/questions/2803071
复制相似问题