使用Armadillo c++在声明后使用辅助内存创建vec

Creating vec with auxiliary memory after declaration with Armadillo c++

本文关键字:内存 创建 vec c++ Armadillo 声明 使用      更新时间:2023-10-16

我正在使用c++中的犰狳矩阵库,我想创建一个使用"辅助内存"的vec。标准的方法是

vec qq(6); qq<<1<<2<<3<<4<<5<<6;
double *qqd = qq.memptr();
vec b1(qqd, 6, false);

所以这里,如果我改变b1中的元素,qq中的元素也会改变,这就是我想要的。然而,在我的程序中,我全局声明了b1向量,所以当我定义它时,我不能调用使b1使用"辅助内存"的构造函数。armadillo中有我想要的功能吗?为什么我得到不同的结果,当我运行下面的代码?

vec b1= vec(qq.memptr(), 3, false); //changing  b1 element changes one of qq's element
vec b1;
b1= vec(qq.memptr(), 3, false); //changing b1 element does not chagne qq's

那么,当它被声明为全局时,我如何使一个向量使用来自另一个向量的内存?

使用全局变量通常不是一个好主意。

然而,如果你坚持使用它们,这里有一种使用全局Armadillo向量的辅助内存的可能方法:

#include <armadillo>
using namespace arma;
vec* x;   // global declaration as a pointer; points to garbage by default
int main(int argc, char** argv) {
  double data[] = { 1, 2, 3, 4 };
  // create vector x and make it use the data array
  x = new vec(data, 4, false);  
  vec& y = (*x);  // use y as an "easier to use" alias of x
  y.print("y:");
  // as x is a pointer pointing to an instance of the vec class,
  // we need to delete the memory used by the vec class before exiting
  // (this doesn't touch the data array, as it's external to the vector)
  delete x;
  return 0;
  }