【问题标题】:how to convert std::vector to std::set without losing the order如何在不丢失顺序的情况下将 std::vector 转换为 std::set
【发布时间】:2016-01-26 19:38:59
【问题描述】:

我正在使用以下代码进行转换:

std::set<ObjectType> s(v.begin(), v.end());

但是,我需要保持矢量元素的顺序。我该怎么做?

【问题讨论】:

  • 使用set唯一原因是它是有序的。如果你想保持vector中元素的顺序,你应该保持vector中的元素。
  • std::unique 可能是您想要的,而不是std::set
  • @Jarod42 我想建议但std::unique 要求对容器进行排序。
  • @eaytan 为什么需要std::set

标签: c++ type-conversion stdvector stdset


【解决方案1】:

如果向量未排序,则不能。 std::set 以升序或降序保持其内容。

如果向量是有序的,那么您只需将std::set 的比较函数设置为用于订购向量的任何值。

你可能想看看:How to remove duplicates from unsorted std::vector while keeping the original ordering using algorithms?

【讨论】:

    【解决方案2】:

    当且仅当您的 vector 按严格的弱排序排序时,您才能执行此操作,例如数字按&lt; 排序。在这种情况下,给set 提供适当的比较对象(用于对vector 进行排序的对象),然后顺序就会合适。

    否则,如果您的vector 未按拟合标准排序,则无法使set 保持原始顺序,因为对元素进行排序是set 的不变量之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 2016-12-06
      • 2021-03-02
      • 2018-05-25
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      相关资源
      最近更新 更多