我正在编写一个函数来对Eigen
中的密集矩阵或数组进行排序,并且还返回排列的索引。该函数如下:
template<typename Derived1, typename Derived2>
typename Derived1::PlainObject sort(const DenseBase<Derived1> &x, DenseBase<Derived2> &indices)
{
typename Derived1::PlainObject y = x.derived();
typename Derived2::PlainObject z = indices.derived();
z.resize(y.rows(), y.cols());
for (int i = 0; i < z.size(); ++i)
z(i) = i;
std::sort(z.data(), z.data() + z.size(), [&](size_t a, size_t b) { return y(a) < y(b); });
for (int i = 0; i < z.size(); ++i)
y(i) = x((int) z(i));
return y;
}
现在,我想以以下方式在一段代码中调用此函数:
const ArrayXXd x = ArrayXXd::Random(5, 5);
ArrayXXi indices;
const ArrayXXd xsort = sort(x, indices);
x
已正确排序,但我希望indices
矩阵/数组能够保存排序过程的索引,但是它为空:|
这里会发生什么?在第一个函数z
(它是indices
的基础派生类型)中正确分配和填充,为什么在函数结束后indices
为空?
非常感谢。
您需要z
作为对indices.derived()
的引用,而不是副本: