使用 std::sort 对集合进行排序

2022-01-07 00:00:00 set c++ stl

我想知道我们是否可以对预先创建的集合进行排序.当我第一次创建集合 s_p2 时,我使用不同的元素 point.getLength() 进行排序.但在用户输入后,我想根据 x 值 point.getX() 对项目进行排序.我该怎么做?

I would like to know if we can sort a pre created set. When I first create the set s_p2, I sort using a different element point.getLength(). but after user input i would like to sort the items according to the x value point.getX(). How i do this ?

set container 好像没有排序功能.我被建议使用矢量.但是集合只能存储唯一元素.

It seems like set container does not have a sort function. And i am advised to use vector. But sets are able to store unique elements only.

Q1:如何根据条件对集合进行排序

Q1: How can i sort a set depending on the criteria

Q2:如果 set 无法做到这一点,那么哪个 STL 容器是最佳选择,我该如何对容器中的元素进行排序.

Q2: If set is unable to do this than which STL container is the best choice and how can i sort the elements in the container.

推荐答案

您不能使用 set,它的排序方式是特定 set 类型的一部分.给定的 set 具有固定的集合顺序,无法更改.

You cannot resort a set, how it sorts is part of the type of the particular set. A given set has a fixed set order that cannot be changed.

您可以相对容易地使用相同的数据创建一个新的set.只需创建一个新的 set,根据新标准进行排序.

You could create a new set with the same data relatively easily. Just create a new set that sorts based on the new criteria.

如果你想在同一个代码中使用两个set,你必须抽象对底层set的访问.

If you want to use the two sets in the same code, you'll have to abstract the access to the underlying set.

现在,如果您正在执行罕见的读取和修改,使用手动排序的 vector 通常是一个更好的主意.您可以使用 std::unique-erase 习惯用法删除重复项.

Now, if you are doing rare reads and modifications, using a vector that you sort manually is often a better idea. You can remove duplicates by using the std::unique-erase idiom.

相关文章