C ++排序字符串数组

时间:2010-05-10 13:50:14

标签: 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);
}

6 个答案:

答案 0 :(得分:41)

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

#include <string>
#include <vector>
#include <algorithm>

std::vector<std::string> stringarray;
std::sort(stringarray.begin(), stringarray.end());

答案 1 :(得分:9)

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

您需要使用std::sort来排序字符串。

具体而言,将std::string投射到void*然后投放到char*是未定义的,并且不起作用。

答案 2 :(得分: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;
}

答案 3 :(得分:1)

您可以使用boost :: sort,如下所示:

#include <vector>
#include <boost/range/algorithm.hpp>

std::vector<std::string> stringarray;
boost::sort(stringarray);

如果你想使用find use boost :: find,就像这样:

std::string findme;
auto offset = boost::find(stringarray, findme) - stringarray.begin()

参见2个有用的函数(m_stringarray应该是ClassA的成员):

const size_t ClassA::GetIdByName(std::string name) const
{
    return (boost::find(this->m_stringarray, name) - this->m_stringarray.begin());
}

const std::string ClassA::GetNameById(size_t id) const
{
    return this->m_stringarray[id];
}

答案 4 :(得分:0)

正如许多人所说,你可以使用std :: sort进行排序,但是当你例如想要从z-a排序时会发生什么?这段代码可能很有用

bool cmp(string a, string b)
{
if(a.compare(b) > 0)
    return true;
else
    return false;
}

int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);

for(int i = 0; i < length; i++)
    cout << words[i] << " ";
cout << endl;
    // output will be: this test is a 

}

如果要颠倒排序顺序,只需修改cmp函数中的符号。

答案 5 :(得分:0)

  

这是 C ++ 的另一种无需使用 即可对字符串数组进行排序的方法。

#include <iostream>
#include <algorithm>

using namespace std;

int main() {
    string WordArray[] = {"AA","DD","CC","BB","ZZ","NN"};
    sort(begin(WordArray), end(WordArray));  /*Sort the Array*/
    for(auto& Word: WordArray){
       cout<<Word<<endl;                     /*Print Every String Element*/
    }
    return 0;
}