【发布时间】: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