Sorting Sets using std::sort(使用 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 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 对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 std::sort 对集合进行排序
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
