Custom Sorting a vector of tuples

前端 未结 4 429
自闭症患者
自闭症患者 2021-02-04 04:22

I have a vector of tuples like

vector> v;

I believe that when the default comparison kicks in for tuple types, i

4条回答
  •  你的背包
    2021-02-04 05:19

    Yes, you can define custom sorting in C++ when you need it. I assume you need it for std::sort, right? Look at the documentation of std::sort, at the second version of the algorithm to be precise, the one which takes the comp argument.

    You have to define a less-than functor, something like this:

    struct CustomLessThan
    {
        bool operator()(tuple const &lhs, tuple const &rhs) const
        {
            return std::get<1>(lhs) < std::get<1>(rhs);
        }
    };
    

    And then use it in std::sort:

    std::sort(v.begin(), v.end(), CustomLessThan());
    

    In C++11, you can make the code much shorter by using a lambda instead of creating a named struct. The examples given at cppreference.com also show this technique.

提交回复
热议问题