Runtimeerror in STL sort

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
lena
New poster
Posts: 28
Joined: Mon Mar 05, 2007 5:44 pm

Runtimeerror in STL sort

Post by lena »

//when I use STL sort in my code ,I always get RunTime error, but when I
write a sort myself , i immediate get AC. Could anybody give me an
answer??

it is in the solve function below.


#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 150

int n;

char a[N][N];
int b[N];

bool com(int x, int y){
return strcmp(a[x],a[y])<=0;
}
void sort(){
int i,j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++){
if(strcmp(a[b],a[b[j]])>0)
{
int k = b;
b = b[j];
b[j] = k;
}
}
}
void solve(){
int i,j;
for(i=0;i<n;i++)
b = i;

// the sort fuction is written myself.
sort();
// i used the following sort function is always get run time error.

// sort(b,b+n,com);
int sum = 0;
for(i=0;i<n;i++)
sum += strlen(a);
for(i=1;i<n;i++){
j = 0;
while(a[b[i-1]][j]&&a[b[i-1]][j]==a[b][j])
++ j;
sum -= j;
}
printf("%d\n",sum);
for(i=0;i<n;i++)
puts(a[b]);
}
int main(){

// freopen("10602.txt","r+",stdin);

int t;

scanf("%d",&t);
while(t--){

scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%s",a);

solve();
}
// while(true){}
return 0;
}
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Post by mf »

Read std::sort's documentation, and what assumptions it makes about your comparison function.

In short, as it applies to your code: com(x, x) must return false.
lena
New poster
Posts: 28
Joined: Mon Mar 05, 2007 5:44 pm

Post by lena »

Thank you ,sir ,I got accept when I change the com() function:




/////////////////////////////////////////////////////////////


#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 150

int n;

char a[N][N];
int b[N];

bool com(int x, int y){
return strcmp(a[x],a[y])<0;
}
void sort(){
int i,j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++){
if(strcmp(a[b[i]],a[b[j]])>0)
{
int k = b[i];
b[i] = b[j];
b[j] = k;
}
}
}
void solve(){
int i,j;
for(i=0;i<n;i++)
b[i] = i;
// the sort fuction is written myself.
// sort();
// i used the following sort function is always get run time error.

sort(b,b+n,com);
int sum = 0;
for(i=0;i<n;i++)
sum += strlen(a[i]);
for(i=1;i<n;i++){
j = 0;
while(a[b[i-1]][j]&&a[b[i-1]][j]==a[b[i]][j])
++ j;
sum -= j;
}
printf("%d\n",sum);
for(i=0;i<n;i++)
puts(a[b[i]]);
}
int main(){

// freopen("10602.txt","r+",stdin);

int t;

scanf("%d",&t);
while(t--){

scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%s",a[i]);

solve();
}
// while(true){}
return 0;
}
jedom
New poster
Posts: 2
Joined: Fri May 30, 2008 12:38 pm

Re: Runtimeerror in STL sort

Post by jedom »

whats kind of error is runtime error 307?
Post Reply

Return to “C++”