Search code examples
c++sortingany

How to sort a vector<any>?


Is it possible to sort vector<any> by using std::sort or somehow else?

I was trying to do smth like this

  vector<any> va{ 55ll, 'a', -1};
   
    sort(va.begin(), va.end(), [](const any& lhs, const any& rhs) { return any_cast<decltype(lhs.type())>(lhs) > any_cast<decltype(lhs.type()>(rhs) });

Solution

  • Is it possible to sort vector by using std::sort or somehow else?

    It is possible. You can do it the same way as sorting anything else: By defining a function to compare two std::any with strict total order.

    any_cast<decltype(lhs.type())>(lhs)
    

    This won't work. std::any::type returns std::type_info, and unless you store an object of type std::type_info in std::any, the std::any_cast will fail.


    There are many ways to order objects of heterogeneous types.

    A relatively simple way is to primarily order by the type of the object. A caveat here is that the order of types is not portable across systems:

    bool
    any_less_type(const std::any& l, const std::any& r)
    {
        auto& lt = l.type();
        auto& rt = r.type();
        return std::type_index(lt) < std::type_index(rt);
    }
    

    Then, objects of same type that are orderable may be further ordered, but that feature may have to be limited to a small set of types as if you were using std::variant.