C++排序字符串数组

use*_*514 18 c++ sorting

我正在尝试排序一个字符串数组,但它没有排序任何东西....我做错了什么?

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 :: sort](http://www.cplusplus.com/reference/algorithm/sort/)并在那里进行不区分大小写的比较. (4认同)
  • 请注意,您也可以在数组上使用`std :: sort`(但是`std :: vector`是个更好的主意):`std :: sort(namesS,namesS + MAX_NAMES);` (2认同)
  • 仅当您具有正确的Unicode不区分大小写的比较时. (2认同)

Shi*_*oko 9

std::qsort继承自标准C库.不起作用.

您需要std::sort用于排序字符串.

具体来说,转换std::stringvoid*然后char*是未定义的,将无法工作.

  • " 不起作用." 它可以工作.这并不是说它应该*可以*起作用. (4认同)

Lou*_*ong 6

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)