c++ - 按长度(单词)对字符串数组进行排序 C++

标签 c++ arrays sorting

我有一个函数可以生成一个单词的所有子序列,我将这些子序列保存在一个结构体中,即字符串数组。现在我想对每个数组进行排序,从最短到最长的子序列。我正在尝试使用 STD sort(),但我不知道如何在我的案例中使用它。有什么建议吗?

结构与功能

struct palavras{
    char palavra[1001];
    char final[1001];
    string store[1000];
    int numero;
}p[1001];

void encontra(const char *s, int n)
{
    string str;
    int nn=0;
    while(*s)
    {
        int x=0;
        while(*(s + x))
        {
            for(int y = 0; y <= x; y++)
                str+=s[y];
                p[n].store[nn]=str;
                nn+=1;
                str.clear();
            x++;
        }
        s++;
    }
    p[n].numero=nn;
}

最佳答案

std::sort 有一个版本接受“比较器”,因此您唯一需要做的就是定义一个比较器,根据长度比较字符串。

struct compare_length {
    bool operator()(const std::string &l, const std::string &r) const {
        return l.size()<r.size();
    }
};

然后你可以使用这个比较器来排序你的单词数组:

std::sort(store, store+n, compare_length());

在 C++11 中,您甚至可以使用 lambda 使其成为单行代码:

std::sort(store, store+n, [](const std::string &l, const std::string &r) { return l.size()<r.size(); });

关于c++ - 按长度(单词)对字符串数组进行排序 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27981349/

相关文章:

关于对象数组的Javascript

python - 在 Python 3 中对字典列表进行排序

Angular 6 - 对所有表列进行排序仅适用于两列而不是所有列

c++ - 设置 subchild 在我展开它们时不在 qtreewidget 中缩进

c - 如果我不能在 if 条件中定义一个变量,我怎样才能减少在这段代码中多次搜索我的数组?

java - 尝试/捕获异常以便我可以返回一个数组值并打印出异常?

matlab - 根据第二个矩阵中给定的顺序对矩阵进行排序 (MATLAB)

c++ - 我可以获得未处理(目标)C++ 异常的堆栈跟踪吗?

C++与类中的成员相同的类

C++ for 循环 : evaluation of condition