std :: sort(来自<algorithm>)崩溃

vrk*_*001 2 c++ linux stl stl-algorithm

下面的程序,一个简单的向量排序,在第二次排序调用时崩溃t> = 17.即使对于t == 100,第一次排序也会成功.挣扎了很长一段时间,但我无法弄清楚出了什么问题.有人可以帮帮我吗?

我已经在MacBook Air和Linux机器上试过了,令人惊讶的是,我看到了同样的结果.

#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;
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*rey 10

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

bool sort_by_n( tc a, tc b )
{
    return a.n <= b.n;
}
Run Code Online (Sandbox Code Playgroud)

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

bool sort_by_n( tc a, tc b )
{
    return a.n < b.n;
}
Run Code Online (Sandbox Code Playgroud)