【发布时间】:2012-09-09 16:06:27
【问题描述】:
我尝试学习了c库stdlib的qsort函数。这甚至在c++ 中也提供。但我不明白如何使用它们对c++ 字符串进行排序。我不确定sizeof() 运算符的参数应该是什么,以及我的compare_str 代码是否正确。我试过这段代码:
#include<iostream>
#include<cstdlib>
using namespace std;
#include<string>
int compare_str( const void *a, const void *b){
string obj = (const char*)a;
string obj1 = (const char*)b;
return obj.compare(obj1);
}
int main(){
string obj[4] = {"fine", "ppoq", "tri", "get"};
qsort(obj, 4, sizeof(obj[0].length()), compare_str);
for( int i=0; i<4; i++)
cout<<obj[i]<<endl;
return 0;
}
我的输出是:
ppoq
tri
get
fine
我无法找出错误。请帮忙。
【问题讨论】:
-
我很怀疑这部分“sizeof(obj[0].length())”