2

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;
    }
4

1 回答 1

11

您需要提供严格的弱排序,但是

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

只是一个弱命令。如果元素相同,则必须返回严格的弱顺序。false您需要将其更改为:

bool sort_by_n( tc a, tc b )
{
    return a.n < b.n;
}
于 2013-11-03T19:45:21.283 回答