【问题标题】:std::sort / Works in test code, but cannot deduce template otherwisestd::sort / 在测试代码中工作,但不能推导出模板
【发布时间】:2018-10-13 20:28:27
【问题描述】:

我想按特征值对特征向量进行排序,我正在使用 Eigen。我尝试了以下帖子 (Sorting eigenvectors by their eigenvalues (associated sorting)),但无法使用 MS VisualStudio 2015 进行编译。

所以我认为这不可能那么难。我只需要按特征值排序,跟踪它们的新旧顺序,然后使用特征向量矩阵。

这在我的测试代码中效果很好:

#include <algorithm>
struct a
{
    double num1;
    int num2;
};

bool acompare(a lhs, a rhs) { return lhs.num1 < rhs.num1; }

int demoSortWithStructure()
{
    a array[5];

    array[0].num1 = 1;
    array[0].num2 = 1;

    array[1].num1 = 5;
    array[1].num2 = 2;

    array[2].num1 = 3;
    array[2].num2 = 3;

    array[3].num1 = 2;
    array[3].num2 = 4;

    array[4].num1 = 4;
    array[4].num2 = 0;

    cout << "before sort" << endl;
    for (int i = 0; i < 5; i++)
        cout << array[i].num1 << "\t" << array[i].num2 << endl;

    std::sort(array, array + 5, acompare);

    cout << "\n\nafter sort" << endl;

    for (int i = 0; i < 5; i++)
        cout << array[i].num1 << "\t" << array[i].num2 << endl;

    return 1;
}

所以,我继续将代码概括如下:

void MyClass::SortEigenValuesAndEigenMatrix(VectorXcd eigenvalue, MatrixXcd eigenvector)
{
    VectorXcd eigenvalueOriginal = eigenvalue;
    MatrixXcd eigenvectorOriginal = eigenvector;
    int noValues = eigenvalue.rows();
    a *array = new a[noValues];

    for (int iValue = 0; iValue < noValues; iValue++)
    {
        array[iValue].index = iValue;
        array[iValue].valueReal = eigenvalue(iValue).real();
    }

    sort(array[0], 
        array[noValues], 
        acompare);

    for (int iValue = 0; iValue < noValues; iValue++)
    {
        int indexNew = array[iValue].index;
        eigenvalue(iValue) = eigenvalueOriginal(indexNew);
        eigenvector.col(iValue) = eigenvectorOriginal.col(indexNew);
    }

}

对于上下文,我的特征值和特征向量被定义为复数,但它们是实数值。所以,我只取真实值,并打算根据真实(有符号)值进行排序。

编译器抛出以下错误:

Severity    Code    Description Project File    Line    Suppression State
Error   C2784   'std::complex<_Other> std::operator -(const _Ty &,const std::complex<_Other> &)': could not deduce template argument for 'const std::complex<_Other> &' from 'a'    testRCWA    d:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm    3203    

我不明白。编译器如何推断使用

std::complex

我的模板不清楚怎么办?我应该在使用排序时显式声明类型吗?为什么在这段代码中会发生这种情况,而在隔离时不会发生?

【问题讨论】:

  • 你的意思是sort(&amp;array[0], &amp;array[noValues], acompare); 吗?
  • 我将结构放入我的包含文件中的代码中,但无法编译。这似乎是问题的根源。
  • 我知道 complex 没有
  • 只需使用std::vector,请编辑您的问题以包含minimal reproducible example
  • 你的问题与错误信息无关,错误信息与代码无关,解决方法与问题无关。

标签: c++ sorting templates eigen


【解决方案1】:

不知何故,将结构定义放入包含文件最终导致模板中的歧义。我不确定如何,但通过将结构(和布尔比较)放入类的定义来解决它。

答案不多……但问题解决了。

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多