【问题标题】:C++ Sorting strings by size and alphabetC ++按大小和字母对字符串进行排序
【发布时间】:2019-08-12 20:42:57
【问题描述】:

所以我必须主要按大小对字符串数组进行排序,这没有任何问题。 然后我尝试以类似的方式按字母顺序对相同大小的那些进行排序,简而言之,结果是一团糟。

代码部分:

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

并说明我所说的“混乱”(从控制台复制)的意思:

  • 椅子
  • 鼠标
  • 角度
  • 沉船
  • 天使

输出如下所示:

  • 天使
  • 椅子
  • 鼠标
  • 角度
  • 沉船

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

【问题讨论】:

  • 你可以使用std::sort吗?
  • 请展示实际编译并产生如您所描述的不良结果的真实代码。由于代码中间有明显的拼写错误,显示的代码将无法编译。尽管您的排序算法中的整体逻辑错误似乎相当明显,但拼写错误(不是粗手指)的性质强烈表明这不是您使用的真实代码,而是经过编辑/乱码/截断的版本;因此,任何尝试的解释都可能没有实际意义,因为这不是正在编译和执行的真实代码。
  • 是的,我可以使用 std::sort。我再次复制粘贴的代码,因为确实比较函数有错字。

标签: c++ string sorting string-length alphabetical


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 2012-12-24
    • 1970-01-01
    • 2017-02-23
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多