对(双精度)实数向量进行排序并获得它们
在 C++ 中,想要对一个冗长的 (2^20
) 实数向量进行排序,显然 sort()
可以做到这一点。在使用 R 之前,我已经习惯了很好的 order()
函数,它产生导致排序向量的排列。
示例:
x = {24, 55, 22, 1}
然后排列
perm = {3, 2, 0, 1}
将原始 x
按升序映射到排序后的 x
。
我可能可以实现一些冒泡排序,它不仅对 x 进行排序,而且对向量 {0,1,2,...}
执行相同的转置并输出两者,但我相信有人一定想到了关于它,尤其是有效地完成了它。
In C++ would like to sort a lengthy (2^20
) vector of reals, obviously sort()
does the trick. Having used R before I was used to the nice order()
function which yields the permutation that leads to the sorted vector.
Example:
x = {24, 55, 22, 1}
Then the permutation
perm = {3, 2, 0, 1}
Maps the original x
to the sorted x
in ascending order.
I can probably implement some bubble sort which does not only sort x but performs the same transpositions on the vector {0,1,2,...}
and outputs both, but I believe someone must have thought about it and especially have done it efficiently.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说最好的方法是创建一个整数 0..N 的向量,然后使用比较函数对该数组进行排序,该比较函数比较您试图找到排序排列的向量的相应元素。类似于:
这最大限度地减少了分配开销,因为我们不会创建任何大型临时对象来进行排序,然后提取最终的排列 - 返回的相同向量是用于排序的临时对象。
I would say the best way would be to create a vector of ints 0..N and then sort that array with a comparison function that compares the corresponding elements of the vector you're trying to find the sorted permutation of. Something like:
This minimizes the allocation overhead, as we don't create any large temporary object that we sort and then extract the final permution -- the same vector that is being returned is the temp for sorting.
您可以使用
std::sort
对 {(24, 0), (55, 2), (22, 0), (1, 1)} 对列表进行排序。它不是特别漂亮,但我通常会这样做:这是测试:
You can use
std::sort
to sort the list of pairs {(24, 0), (55, 2), (22, 0), (1, 1)}. It isn't particularly pretty, but I usually do something like this:Here is the test:
编辑
比以前更好的方法,无需使用辅助向量:(ideone 上的来源):
我正在使用 C++0x 中的 lambda,但它可以用简单的函子对象替换:
带有
std::map
的旧解决方案的来源:ideoneEdit
Better than before approach without using helper vectors: (source on ideone):
I am using lambda from C++0x, but it can be replaced with simple functor object:
Source of old solution with
std::map
: ideone