首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >字符串数组的C++排序

字符串数组的C++排序
EN

Stack Overflow用户
提问于 2010-05-10 21:50:14
回答 5查看 82.2K关注 0票数 21

我正在尝试对字符串数组进行排序,但它没有对任何内容进行排序...我做错了什么?

代码语言:javascript
复制
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);
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-05-10 22:00:04

这是C++,不是C。对字符串数组进行排序很容易。

代码语言:javascript
复制
#include <string>
#include <vector>
#include <algorithm>

std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());
票数 49
EN

Stack Overflow用户

发布于 2010-05-10 21:54:08

std::qsort继承自标准C库。这是行不通的。

您需要使用std::sort对字符串进行排序。

具体地说,先将std::string转换为void*,然后再转换为char*,这是未定义的,不会起作用。

票数 10
EN

Stack Overflow用户

发布于 2010-05-26 01:54:40

CPP中的算法sort与qsort具有相同的复杂度:

代码语言:javascript
复制
#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;
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2803071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档