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

简介: 从 3.4 版本开始,Eigen 的稠密矩阵和数组提供了 STL 兼容的迭代器。这使 Eigen 自然地与 range-for 循环和 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
相关文章
|
6月前
|
算法 搜索推荐 C++
【C++STL基础入门】vector运算和遍历、排序、乱序算法
【C++STL基础入门】vector运算和遍历、排序、乱序算法
|
1月前
|
存储 算法 JavaScript
【C++ 泛型编程 入门篇】 C++ 中的泛型算法 STL(sort,find)(二)
【C++ 泛型编程 入门篇】 C++ 中的泛型算法 STL(sort,find)
28 0
|
1月前
|
算法 搜索推荐 程序员
【C++ 泛型编程 入门篇】 C++ 中的泛型算法 STL(sort,find)(一)
【C++ 泛型编程 入门篇】 C++ 中的泛型算法 STL(sort,find)
35 0
|
2月前
|
存储 算法 搜索推荐
C++模板与STL【常用算法】
C++模板与STL【常用算法】
|
2月前
|
算法 C++ 容器
【C++】 --- STL常用算法总结(三)
【C++】 --- STL常用算法总结
27 0
|
2月前
|
存储 算法 搜索推荐
【C++】 --- STL常用算法总结(二 )
【C++】 --- STL常用算法总结
35 0
|
2月前
|
算法 C++ 容器
【C++】 --- STL常用算法总结(一)
【C++】 --- STL常用算法总结
33 0
|
3月前
|
算法 C++ 容器
【C++STL基础入门】list的运算符重载和关于list的算法
【C++STL基础入门】list的运算符重载和关于list的算法
【C++STL基础入门】list的运算符重载和关于list的算法
|
4月前
|
算法 vr&ar 图形学
☆打卡算法☆LeetCode 173. 二叉搜索树迭代器 算法解析
☆打卡算法☆LeetCode 173. 二叉搜索树迭代器 算法解析
|
4月前
|
算法 搜索推荐 C++
C++ STL容器和算法:详解和实例演示
C++ STL(标准模板库)提供了一组丰富的容器和算法,使得开发者能够更加高效地编写程序。本文将介绍STL中的一些常用容器和算法。
113 0