c++ - 带有 boost ublas 的常数矩阵

标签 c++ boost constants boost-ublas

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

[1 2 3
 4 5 6
 7 8 9] 

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

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

代码如下:

测试.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_ */

测试.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};

最佳答案

使用 <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是从 here 复制的最小工作示例

关于c++ - 带有 boost ublas 的常数矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48821973/

相关文章:

c++ - boost 目录迭代器错误 : no match for operator! =

c++ - 使用 boost::function 作为函数参数?

gcc - C/C++编译器(例如GCC)是否通常以2的幂次幂来优化模数?

c++ - Const 改变变量值

c++ - 模板类的模板化相等运算符不编译

具有共享 Dlib 库的 C++ 程序在 Ubuntu 14.04 上速度极慢

c++ - ui上的qt c++神秘的不完整类类型错误

c++ - 在 QtCreator 中跳过第二个自动生成的报价

c - 像 C 中的库一样 boost

c++ - Visual Studio 等中datatype&const var_name 的实现差异