stl sort 的comp 函数对象

 

下面代码会core:

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <new>

struct foo_t
{
    int size;
};

class cmp_t
{
public:
    bool operator()(foo_t *a, foo_t *b)
    {
        return a->size >= b->size;
    }
};

int main(int argc, char *argv[])
{
    std::vector<foo_t *> vec;

    for (int i = 0; i < 17; i++)
    {
        foo_t *x = new(std::nothrow) foo_t();
        if (NULL == x)
        {
            goto fail;
        }
        else
        {
            x->size = 1;
        }
        vec.push_back(x);
    }

    std::sort(vec.begin(), vec.end(), cmp_t());
    cout << "good " << endl;
fail:
    for(std::vector<foo_t *>::iterator iter = vec.begin(); vec.end() != iter; ++iter)
    {
        delete *iter;
        *iter = NULL;
    }

    return 0;
}

  

改成

return a->size > b->size; 后即可

posted on 2018-08-09 16:23  不忘初衷,方能致远  阅读(198)  评论(0)    收藏  举报

导航