我有一个函数可以生成一个单词的所有子序列,我将这些子序列保存在一个结构体中,即字符串数组。现在我想对每个数组进行排序,从最短到最长的子序列。我正在尝试使用 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/