C ++按大小和字母对字符串进行排序

问题描述 投票:-1回答:1

所以我必须主要按大小排序一个字符串数组,没有任何问题。然后我尝试按照类似的方式按字母顺序对相同大小的那些进行排序,并将其简单地称为完全混乱。

代码部分:

#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;
}

并通过“混乱”(从控制台复制)显示我的意思输入:

  • 椅子
  • 老鼠
  • 角度
  • 破坏
  • 天使

输出如下所示:

  • 天使
  • 椅子
  • 老鼠
  • 角度
  • 破坏

所以它没有什么接近排序,我不知道我可以尝试使它有什么不同的方式。

c++ string sorting string-length alphabetical
1个回答
0
投票

你比较函数应该是这样的:

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;
}

但更简单的是使用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);
© www.soinside.com 2019 - 2024. All rights reserved.