C 分类字符串按大小和字母表

C++ Sorting strings by size and alphabet

本文关键字:字母表 分类 字符串      更新时间:2023-10-16

因此,我必须按大小对字符串进行排序,这些字符串毫无问题。然后,我尝试以类似方式将字母顺序排序相同的大小,然后简单地将其作为完整的烂摊子出现。

代码部分:

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

并显示我的意思是输入:

的" Mess"(从控制台复制)
  • 主席
  • 鼠标
  • 角度
  • 残骸
  • 天使

输出看起来像这样:

  • 天使
  • 主席
  • 鼠标
  • 角度
  • 残骸

所以这没有什么接近分类的,我不知道我可以尝试使它起作用的方式有何不同。

您比较函数应该是:

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