本文介绍了使用std :: sort排序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我们是否可以对预先创建的集合进行排序.首次创建集合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容器没有排序功能.并且我建议使用向量.但是集合只能存储唯一元素.

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.

问题1:如何根据条件对集合进行排序

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.

这篇关于使用std :: sort排序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 01:32
查看更多