Domanda

The following program, a simple vector sorting one, crashes for t >= 17 at the second sort invocation. First sort succeeds even for t == 100. Struggled for quite some time but I'm not able to figure out what is wrong. Can someone please help me?

I've tried it on a MacBook Air as well as a linux machine and, surprisingly, I am seeing the same result.

#include<iostream>
#include<vector>
#include<algorithm>

    using namespace std;
    struct tc
    {
        unsigned int n;
    };
    bool sort_by_n( tc a, tc b )
    {
        return a.n <= b.n;
    }
    vector<tc> tcv(100);
    vector<int> tv(100);
    int main()
    {
        unsigned int t;
        cin >> t;
        for ( unsigned int i = 0 ; i < t ; i++ )
        {
            cin >> tcv[i].n;
            tv[i] = tcv[i].n;
        }
        sort( tv.begin(), tv.begin()+t); // ## This one works even for t == 100.
        sort( tcv.begin(), tcv.begin()+t, sort_by_n ); // ## This one crashes for t >= 17
        return 0;
    }
È stato utile?

Soluzione

You need to provide a strict weak ordering, but

bool sort_by_n( tc a, tc b )
{
    return a.n <= b.n;
}

is only a weak order. A strict weak order must return false if the elements are the same. You need to change it to:

bool sort_by_n( tc a, tc b )
{
    return a.n < b.n;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top