### AnasAbbas's blog

By AnasAbbas, history, 4 years ago,

hello everyone

i'm trying to sort a vector using an explicit compare function

why does this simple code gives me Runtime Error sometimes and sometime Time Limit Exceeded

• +3

 » 4 years ago, # |   +5 Short answer: You should change: cost(f)<=cost(s) to cost(f)
•  » » 4 years ago, # ^ |   0 can you give me the long answer please ?
•  » » » 4 years ago, # ^ | ← Rev. 2 →   +14 Here are the requirements for a Compare function: cppreference Basically the compare function needs to define a strict weak ordering. If your compare function returns true, you're telling the sort function that the first value has to appear before the second element. So if cost(f) == cost(s), then the program thinks that the value f has to appear before s, and also s has to appear before f (because cost(s) == cost(f)). So it doesn't know what to do and gives a runtime error.
•  » » » 4 years ago, # ^ | ← Rev. 2 →   0 Maybe this is helpful?EDIT: Sniped
•  » » » 4 years ago, # ^ |   +5 Jakubethank you very much
 » 4 years ago, # | ← Rev. 4 →   0 I have just tried to compile and run your code using GNU C++17 Custom Invocation in CF #include using namespace std; int cost(int in) { return in; } bool comp( const int f, const int s ) { return cost(f) <= cost(s); } int main() { auto x = vector( 100000, 0 ); sort( x.begin(), x.end(), comp ); cout << "Done" << endl; } The following is the program output:Done=====Used: 2839 ms, 3660 KBThe following is the program output after replacing the <= operator with < operator in the comp function.Done=====Used: 15 ms, 3680 KB
•  » » 4 years ago, # ^ |   0 i really don't know why this worked ,, sorry