How to sort an STL vector?

前端 未结 5 2258
借酒劲吻你
借酒劲吻你 2020-12-04 10:44

I would like to sort a vector

vector object;

Where myclass contains many int variabl

5条回答
  •  春和景丽
    2020-12-04 11:17

    std::sort(object.begin(), object.end(), pred());
    

    where, pred() is a function object defining the order on objects of myclass. Alternatively, you can define myclass::operator<.

    For example, you can pass a lambda:

    std::sort(object.begin(), object.end(),
              [] (myclass const& a, myclass const& b) { return a.v < b.v; });
    

    Or if you're stuck with C++03, the function object approach (v is the member on which you want to sort):

    struct pred {
        bool operator()(myclass const & a, myclass const & b) const {
            return a.v < b.v;
        }
    };
    

提交回复
热议问题