如何对向量进行排序?

发布于 2025-01-18 05:43:21 字数 1488 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见你 2025-01-25 05:43:21

是否可以使用 std::sort 或其他方式对向量进行排序?

这是可能的。您可以采用与排序任何其他内容相同的方式来完成此操作:通过定义一个函数来比较两个具有严格总顺序的 std::any

any_cast(lhs)

这行不通。 std::any::type 返回 std::type_info,除非您在 中存储 std::type_info 类型的对象std::any 时,std::any_cast 将失败。


有多种方法可以对异构类型的对象进行排序。

一个相对简单的方法是主要按对象的类型排序。这里需要注意的是,类型的顺序不可跨系统移植:

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);
}

然后,可排序的相同类型的对象可能会进一步排序,但该功能可能必须仅限于一小组类型,就像您使用 std::变体

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文