Hekmatyar
Hekmatyar

Reputation: 405

C++ Sorting strings by size and alphabet

So I have to sort an array of strings primarily by size which works without any problem. Then I try to alphabetically sort those of the same size in a similar way and to put it simply it comes out as complete mess.

Code part:

#include <iostream>
#include <string>

using namespace std;

struct strs{
    string str;
    int sz; //stores size of the string
};

bool compare(string a, string b, int s){ //comparing by characters
    for(int i = 0; i < s; i++){
        if(a[i] > b[i]) return true;
    }

    return false;
}

int main(){
    int n, chk;
    bool ctr;

    cin>>n;

    strs tab[n];

    for(int i = 0; i < n; i++){
        cin>>tab[i].str;

        tab[i].sz = tab[i].str.size();
    }

    //Comparing lengths
    for(int i = 0; i < n; i++){
        chk = i;

        for(int j = i + 1; j < n; j++){

            if(tab[chk].sz > tab[j].sz){
                chk = j;
            }
        }

        if(chk != i){
            swap(tab[i].str, tab[chk].str);
            swap(tab[i].sz, tab[chk].sz);
        }
    }

    //Comparing characters
    for(int i = 0; i < n; i++){
        chk = i;

        for(int j = i + 1; j < n; j++){

            if(tab[chk].sz == tab[j].sz){

                ctr = compare(tab[chk].str, tab[j].str, tab[chk].sz);
                if(ctr) chk = j;

            }

            if(tab[i].sz < tab[j].sz) break;
        }

        if(chk != i){
            swap(tab[i].str, tab[chk].str);
            swap(tab[i].sz, tab[chk].sz);
        }
    }

    //output
    for(int i = 0; i < n; i++){
        cout<<tab[i].str<<endl;
    }

    return 0;
}

And to show what I mean by "mess" (copying from console) for input:

The output looks like this:

So it's nothing close to being sorted and I have no idea what different way I could try to make it work.

Upvotes: 1

Views: 2761

Answers (1)

Jarod42
Jarod42

Reputation: 217810

You compare function should be something like:

bool compare(const std::string& a, const std::string& b, int s){ //comparing by characters
    for(int i = 0; i < s; i++){
        if(a[i] != b[i]) return a[i] > b[i];
    }
    return false;
}

but simpler is using std::sort:

auto proj = [](const std::string& s){ return std::make_tuple(s.size(), std::ref(s)); };
auto compare = [](const std::string& lhs, const std::string& rhs)
{
    return proj(lhs) < proj(rhs);
};

std::sort(strings.begin(), strings.end(), compare);

Upvotes: 1

Related Questions