问题描述
我想知道我们是否可以对预先创建的集合进行排序.当我第一次创建集合 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.
这篇关于使用 std::sort 对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)