繁体   English   中英

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

[英]Creating vec with auxiliary memory after declaration with Armadillo c++

我在c ++中使用armadillo矩阵库,并且想创建一个使用“辅助内存”的vec。 执行此操作的标准方法是

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

因此,在这里,如果我更改b1中的元素,那么qq中的元素也会更改,这就是我想要的。 但是,在我的程序中,我声明了b1向量全局,因此,在定义它时,我无法调用使b1使用“辅助内存”的构造函数。 犰狳中有我想要的功能吗? 当我运行下面的代码时,为什么会得到不同的结果?

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;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM