C++ Sort()导致分段错误
我必须实现一个shuffleString(strings,intd)方法,其中第一步是获取字符串中每个字符的计数,并将它们按计数的降序排列。我实现了所需的功能,如下所示:C++ Sort()导致分段错误,c++,string,stl,C++,String,Stl,我必须实现一个shuffleString(strings,intd)方法,其中第一步是获取字符串中每个字符的计数,并将它们按计数的降序排列。我实现了所需的功能,如下所示: struct node{ char ch; int ctr; }; bool myfunc(const struct node x,const struct node y){ return (x.ctr>=y.ctr?true:false); } string shuffleString
struct node{
char ch;
int ctr;
};
bool myfunc(const struct node x,const struct node y){
return (x.ctr>=y.ctr?true:false);
}
string shuffleString(string s,int d){
int i,j;
int len=s.size();
vector<struct node> counter(26);
for(i=0;i<26;i++){
counter[i].ch='a'+i;
counter[i].ctr=0;
}
for(i=0;i<len;i++){
counter[s[i]-'a'].ctr++;
}
sort(counter.begin(),counter.end(),myfunc);//From STL's algorithm
/*
Remaining Functionality
*/
}
struct节点{
char ch;
国际中心;
};
bool myfunc(常量结构节点x,常量结构节点y){
返回(x.ctr>=y.ctr?真:假);
}
字符串串串(字符串s,整数d){
int i,j;
int len=s.size();
向量计数器(26);
对于(i=0;i您可能在以下行中出现内存损坏:counter[s[i]-'a'].ctr++
s[i]-“a”可以大于25,超出向量边界。stl sort默认使用运算符
与运算符一样是非自反的请尝试此操作
bool myfunc(常量结构节点x,常量结构节点y){
返回(x.ctr>y.ctr)| |(x.ctr==y.ctr&&x.ch
编辑:
您应该处理断接案例(分开
和=
案例,而不是=
)
当输入包含除a-z
(甚至a-z
)以外的任何字符时,您的算法将失败
这里有一个小片段:
struct node{
char ch;
int ctr;
};
bool myfunc(const struct node x,const struct node y){
return (x.ctr>y.ctr) || (x.ctr == y.ctr && x.ch < y.ch);
}
void shuffleString(string s){
int i,j;
int len=s.size();
vector<struct node> counter(26);
for(i=0;i<26;i++){
counter[i].ch='a'+i;
counter[i].ctr=0;
}
for(i=0;i<len;i++){
counter[s[i]-'a'].ctr++;
}
for(int i=0; i<26;i++) cout << counter[i].ch <<"," << counter[i].ctr << endl;
cout << endl << endl;
sort(counter.begin(),counter.end(), myfunc);//From STL's algorithm
for(int i=0; i<26;i++) cout << counter[i].ch <<"," << counter[i].ctr << endl;
}
int main()
{
shuffleString("hello");
return 0;
}
struct节点{
char ch;
国际中心;
};
bool myfunc(常量结构节点x,常量结构节点y){
返回(x.ctr>y.ctr)| |(x.ctr==y.ctr&&x.ch for(i=0;我到目前为止你做了什么?想不出多少…在myfunc()方法中写了一个print语句。sort方法似乎在无休止地运行。此外,当我删除station返回中的“=”时(x.ctr>=y.ctr?true:false)'程序似乎正在执行。字符串中只有小写ASCII字符。问题已编辑。但是删除“=”将更改相对顺序??无论如何……谢谢..我收到了错误。