我很难确定如何返回对 Armadillo vector 元素的引用。

例如

arma::vec3 v = arma::zeros(3);
v.at(0) = 1; // works as expected, surely this means the at() method returns a reference?

但是,这不能编译:
struct Custom {
  arma::vec3 v;
  double& x() { return v.at(0) }
}
Custom custom;
custom.x() = 1;

错误如下:



我认为这是因为at()返回的是副本而不是引用,但是前面的示例如何工作?

我相信这可能是由于 Armadillo 的胶水类型返回的,而不是真正的“双”胶水,但是我找不到关于这些胶水的任何文档,所以我不确定如何使用它们。

回答

下面的方法起作用,给 vector 元素提供“类似引用”的命名访问。
inline double x() const { return at(0); }
inline double& x() { return at(0); }

inline double y() const { return at(1); }
inline double& y() { return at(1); }

inline double z() const { return at(2); }
inline double& z() { return at(2); }

inline const arma::subview_col<double> xy() const { return rows(0,1); }
inline arma::subview_col<double> xy() { return rows(0,1); }

最佳答案

at(0)几乎肯定会返回一个代理对象,该对象可以转换为double,也可以分配一个double,但实际上不是引用。这可能是为了避免引用悬而未决,或者是为了有效地存储稀疏矩阵。不幸的是,Armadillo的documentation在语义上非常安静,但未指定at返回引用。

这建议您不要返回引用。还有另一种方式来实现您想要的吗?

10-07 19:38
查看更多