在访问Eigen::VectorXd时使用0作为第二个索引是否安全?
Is it safe to use zero as second index in accessing Eigen::VectorXd?
Eigen::VectorXd
有一个Scalar operator()(Index i)
,它返回向量中索引i
处的系数。但是,由于Eigen::VectorXd
是Eigen::Matrix
的特殊类型,即Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
类型,因此还存在Scalar operator()(Index i, Index j)
。
问题:
我可以假设它是安全的(即没有未定义的行为)使用第二个版本,如果我设置j
为零?换句话说,下面的代码可以吗?
Eigen::VectorXd v(4);
v << 1, 2, 3, 4;
std::cout << v(2, 0); // displays 3
看起来很好,在调试模式下编译时没有失败的断言或警告,但我不是100%确定。
只要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));
我将详细说明@ggaels的答案。如果您查看DenseCoeffsBase.h中的operator()
定义(我引用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);
}
查看PlainObjectBase.h中coeffRef的定义,我们看到偏移量的计算很简单:
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)
以避免可能的断言失败/越界错误。
相关文章:
- 如何在for循环中包含两个索引值的测试条件
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 查找字符在两个索引之间出现的次数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 将第二个 GATT 服务添加到 Movesense 容器
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 为什么 Boost multi_index只修改第一个索引的键时对第二个索引进行比较?
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 我正在尝试将我的 c++ 数组从第二个索引切到最后一个索引
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- C++ 2D 数组起作用 - 为什么第二个索引不能是可变的
- 使用c++中的第二个索引数组对数组进行排序
- 在访问Eigen::VectorXd时使用0作为第二个索引是否安全?