C++ sort array of strings

后端 未结 6 1874
渐次进展
渐次进展 2021-01-01 15:28

I am trying to sort an array of strings, but it\'s not sorting anything.... what am I doing wrong?

string namesS[MAX_NAMES];

int compare (const void * a, co         


        
6条回答
  •  爱一瞬间的悲伤
    2021-01-01 15:50

    As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful

    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 
    
    }
    

    If you want to reverse the order of sorting just modify the sign in the cmp function.

提交回复
热议问题