C 分类字符串按大小和字母表
C++ Sorting strings by size and alphabet
因此,我必须按大小对字符串进行排序,这些字符串毫无问题。然后,我尝试以类似方式将字母顺序排序相同的大小,然后简单地将其作为完整的烂摊子出现。
代码部分:
#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);
相关文章:
- 如何在C++中移动字母表中的字母?
- 循环回到z之后的字母表的开头
- C 分类字符串按大小和字母表
- 我在使用布尔函数时遇到问题,其中用户输入两个字母并输出字母表中最高的字母
- 使用列表向后打印字母表时缺少'a'
- 警告:数组"字母表"由括号字符串文本初始化
- 如何检查字符是否是某个字母表中的字母
- 为什么在此 C 代码中将字母表拆分为多个范围?
- c++如何确定字母表中一个单词是否在另一个单词之前
- 计算C++中每个字母表的出现次数
- 求字母表{a,b,c}上长度为n的字符串w的个数
- 如何检查字母表中的字母在文本文件中出现的次数C++
- 将莫尔斯值解码为字母表
- 在 C 语言中,求解从字母表中输入的整数并重复循环
- 迭代C/C++中的字母表
- 制作一个程序来计算字母表中每个字母的出现次数
- C++编程中的字母表到星形
- 按字母表对字符串数组进行排序并显示值
- 找出字母表中一个字母对应的数字
- 土耳其字母表的凯撒密码解密