immiao
immiao

Reputation: 102

Why do I get Runtime Error when comparison function in std::sort always return true?

Why do I get Runtime Error when comparison function in std::sort always return true?

bool compare(string a, string b)
{
    return true;
}

vector<string> Test;
for (int i = 0; i < 7; i++)
    Test.push_back(string("0"));
sort(Test.begin(), Test.end(), compare);

Upvotes: 2

Views: 1818

Answers (2)

Malcolm McLean
Malcolm McLean

Reputation: 6404

You write qsort by taking an item at random, then separating all the input into "bigger" and "smaller" piles. Then you do the same to both of the piles. It only works if you more or less halve each pile on each step. If the comparison function always returns true, everything goes into the "bigger" pile, and thus the recursion never stops until the stack is exhausted and the computer reports an error.

That's probably what is happening.

Upvotes: 0

eerorika
eerorika

Reputation: 238311

The comparison function must meet the requirements of Compare concept. One of the requirements is:

If comp(a,b)==true then comp(b,a)==false

Your function violates this requirement, so the program has undefined behaviour.

Upvotes: 15

Related Questions