接受DenseBase的非常量引用 并将其填充到函数中不起作用

问题描述 投票:0回答:1

我正在编写一个函数来对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为空?

非常感谢。

c++ eigen
1个回答
1
投票

您需要z作为对indices.derived()的引用,而不是副本:

© www.soinside.com 2019 - 2024. All rights reserved.