带有 boost ublas 的常数矩阵

Constant matrix with boost ublas

我想像这样定义一个带有 boost 的常量 3x3 矩阵,它在执行过程中永远不会改变:

[1 2 3
 4 5 6
 7 8 9] 

此矩阵将是 class 的成员。那么,我可以像基本类型一样将常量矩阵变量定义并初始化为 class 成员吗?当我尝试为 someMatrix 变量键入 const 时,我无法在构造函数中分配矩阵数据并出现此错误:

error: assignment of read-only location '((Test*)this)->Test::someMatrix.boost::numeric::ublas::matrix<double>::operator()(0, 0)'

代码如下:

Test.h

#ifndef TEST_H_
#define TEST_H_

#include <boost/numeric/ublas/matrix.hpp>

namespace bnu = boost::numeric::ublas;

class Test {
private:
    const double a = 1;
    const double b = 2;
    const double c = 3;
    const double d = 4;
    const double e = 5;
    const double f = 6;
    const double g = 7;
    const double h = 8;
    const double i = 9;
    const bnu::matrix<double> someMatrix;

public:
    Test();
    virtual ~Test();
};

#endif /* TEST_H_ */

Test.cpp

Test::Test(){
    someMatrix(0,0) = a;
}

Main.cpp

include "Test.h"

int main() {
    Test * t = new Test();

}

我真正想要的是找到一种方法来定义 someMatrix,如下所示:

const bnu::matrix<double> someMatrix(3,3) = {a,b,c,d,e,f,g,h,i};

您可以编写一个辅助函数来执行此操作

class Test {
private:
    const bnu::matrix<double> someMatrix;
    static bnu::matrix<double> initSomeMatrix();
public:
    Test();
    virtual ~Test();
}

Test::Test() : someMatrix(initSomeMatrix()) {
}

bnu::matrix<double> Test::initSomeMatrix() {
    bnu::matrix<double> temp(3, 3);
    temp(0,0) = 1;
    ...
    return temp;
}

RVO 应该使这相当有效。

使用 <boost/numeric/ublas/assignment.hpp>,您可以使用 <<= 将值插入 ublas::matrixublas::vector,这样您就可以像这样实例化矩阵:

bnu::matrix<double> a(3,3); a <<=  0, 1, 2,
                                   3, 4, 5,
                                   6, 7, 8;

要使其保持不变,只需复制它即可:

const bnu::matrix<double> b = a;

HERE is a working minimal example copied from here