Is it safe to use zero as a second index when accessing Eigen :: VectorXd?

Eigen::VectorXdhas Scalar operator()(Index i), which returns the coefficient in the index iin the vector. However, since it Eigen::VectorXdis a special type Eigen::Matrix, that is, a type Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;also exists Scalar operator()(Index i, Index j).

Question:

Can it be considered safe (i.e., undefined behavior) to use the second version if I set it jto zero? In other words, is the code below OK?

Eigen::VectorXd v(4);
v << 1, 2, 3, 4;
std::cout << v(2, 0); // displays 3

It seems that everything is in order, there are no failed statements or warnings when compiling in debug mode with all warnings, but I'm not 100% sure.

+4
source share
2 answers

, v , v(i) , , :

template<typename T>
void foo(const T &v) {
  v(2);   // OK
  v(2,0); // -> out of bounds runtime assertion
}
MatrixXd mat(10,10);
foo(mat.row(5));
+4

@ggaels . operator() DenseCoeffsBase.h( 3.2.10), , coeff ( coeffRef)

EIGEN_STRONG_INLINE CoeffReturnType operator()(Index row, Index col) const
{
  eigen_assert(row >= 0 && row < rows()
      && col >= 0 && col < cols());
  return derived().coeff(row, col);
}

EIGEN_STRONG_INLINE CoeffReturnType
operator()(Index index) const
{
  eigen_assert(index >= 0 && index < size());
  return derived().coeff(index);
}

coeffRef PlainObjectBase.h, , :

EIGEN_STRONG_INLINE Scalar& coeffRef(Index rowId, Index colId)
{
  if(Flags & RowMajorBit)
    return m_storage.data()[colId + rowId * m_storage.cols()];
  else // column-major
    return m_storage.data()[rowId + colId * m_storage.rows()];
}

EIGEN_STRONG_INLINE Scalar& coeffRef(Index index)
{
  return m_storage.data()[index];
}

, v(0,2), / .

+2

Source: https://habr.com/ru/post/1657548/


All Articles