c++ - 返回对 Armadillo vector 元素的引用

标签 c++ armadillo

我很难确定如何返回对 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;

错误如下:

error: invalid initialization of reference of type ‘double&’ from expression of type ‘const double’

我假设这是因为 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,但实际上不是引用。这可能是为了避免悬挂引用,或允许高效存储稀疏矩阵。 documentation不幸的是,Armadillo 在语义上非常安静,但它没有指定 at 返回一个引用。

这表明您不希望返回引用。有没有其他方法可以实现您想要的?

关于c++ - 返回对 Armadillo vector 元素的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27703507/

相关文章:

c++ - 请帮助我理解 Boost::Any

r - RcppArmadillo 中的函数通过引用传递

c++ - 从 HDF5 vector 填充 Armadillo vec

c++ - 在 C++ 上的 Armadillo 中,稀疏矩阵上的 sum(<sp_mat>,<dim>) 不起作用

c++ - 这个 GNU 对三元运算符的扩展有多广泛?

c++ - Qt Layout/Widget 交互 - Layouts within Layouts

c++ - 如何从 C++ 程序中的文件名命令行参数确定完整路径?

c++ - C++ 中的这种隐式转换是如何发生的?

c++ - Armadillo 乘法的差异

c++ - 从双指针在 oct 文件中创建 NDArray