在 C++ 中想要对很长的 (2^20
) 实数向量,显然sort()
就可以了。在我习惯了 R 的优点之前就已经使用过 Rorder()
函数产生导致排序向量的排列。
Example:
x = {24, 55, 22, 1}
然后是排列
perm = {3, 2, 0, 1}
贴出原图x
到已排序的x
按升序排列。
我可能可以实现一些冒泡排序,它不仅对 x 进行排序,而且对向量执行相同的转置{0,1,2,...}
并输出两者,但我相信一定有人考虑过它,尤其是有效地做到了这一点。
我想说最好的方法是创建一个整数 0..N 的向量,然后使用比较函数对该数组进行排序,该比较函数比较您试图找到排序排列的向量的相应元素。就像是:
#include <vector>
#include <algorithm>
template<class T> class sorter {
const std::vector<T> &values;
public:
sorter(const std::vector<T> &v) : values(v) {}
bool operator()(int a, int b) { return values[a] < values[b]; }
};
template<class T> std::vector<int> order(const std::vector<T> &values)
{
std::vector<int> rv(values.size());
int idx = 0;
for (std::vector<int>::iterator i = rv.begin(); i != rv.end(); i++)
*i = idx++;
std::sort(rv.begin(), rv.end(), sorter<T>(values));
return rv;
}
这最大限度地减少了分配开销,因为我们不会创建任何大型临时对象来进行排序,然后提取最终的排列 - 返回的相同向量是用于排序的临时对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)