[Eigen中文文档] STL迭代器和算法

文档总目录

英文原文(STL iterators and algorithms)

从 3.4 版本开始,Eigen 的稠密矩阵和数组提供了 STL 兼容的迭代器。这使 Eigen 自然地与 range-for 循环和 STL 算法兼容。

遍历一维数组和向量

任何稠密一维表达式都支持begin()/end()方法以进行迭代。

如下使用C++11的 range-for 循环:

// 代码索引 3-9-1-1
VectorXi v = VectorXi::Random(4);
cout << "Here is the vector v:\n";
for(auto x : v) cout << x << " ";
cout << "\n";

输出:

Here is the vector v:
7 -2 6 6 

一维表达式也可以轻松传给 STL 算法:

// 代码索引 3-9-1-2
Array4i v = Array4i::Random().abs();
cout << "Here is the initial vector v:\n" << v.transpose() << "\n";
std::sort(v.begin(), v.end());
cout << "Here is the sorted vector v:\n" << v.transpose() << "\n";

输出:

Here is the initial vector v:
7 2 6 6
Here is the sorted vector v:
2 6 6 7

std::vector 类似,一维表达式也有一对 cbegin()/cend() 方法,以方便地获取非 const 对象上的 const 迭代器。

迭代二维数组和矩阵的元素

STL 迭代器本质上是设计用于迭代一维结构的。这就是二维表达式禁用 begin()/end() 方法的原因。但通过 reshaped() 创建二维表达式的一维线性对象,仍然可以轻松地迭代二维表达式的所有元素。

示例:

// 代码索引 3-9-1-3
Matrix2i A = Matrix2i::Random();
cout << "Here are the coeffs of the 2x2 matrix A:\n";
for(auto x : A.reshaped())
  cout << x << " ";
cout << "\n";

输出:

Here are the coeffs of the 2x2 matrix A:
7 -2 6 6 

迭代二维数组和矩阵的行或列

也可以在二维表达式的行或列上使用迭代器。这可以通过 rowwise()colwise() 代理实现。如下是对矩阵的每一行进行排序的示例:

// 代码索引 3-9-1-4
ArrayXXi A = ArrayXXi::Random(4,4).abs();
cout << "Here is the initial matrix A:\n" << A << "\n";
for(auto row : A.rowwise())
  std::sort(row.begin(), row.end());
cout << "Here is the sorted matrix A:\n" << A << "\n";

输出:

Here is the initial matrix A:
7 9 5 3
2 6 1 0
6 3 0 9
6 6 3 9
Here is the sorted matrix A:
3 5 7 9
0 1 2 6
0 3 6 9
3 6 6 9
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万俟淋曦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值