> 文章列表 > [Eigen中文文档] STL迭代器和算法

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

[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