STL iterators and algorithms

Since the version 3.4, Eigen's dense matrices and arrays provide STL compatible iterators. As demonstrated below, this makes them naturally compatible with range-for-loops and STL's algorithms.

Iterating over 1D arrays and vectors

Any dense 1D expressions exposes the pair of begin()/end() methods to iterate over them.

This directly enables c++11 range for loops:

Example:Output:
cout << "Here is the vector v:\n";
for(auto x : v) cout << x << " ";
cout << "\n";
Array< int, Dynamic, 1 > v
static const RandomReturnType Random()
Definition: Random.h:114
Matrix< int, Dynamic, 1 > VectorXi
Dynamic×1 vector of type int.
Definition: Matrix.h:500
Here is the vector v:
7 -2 6 6 

One dimensional expressions can also easily be passed to STL algorithms:

Example:Output:
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";
Array< int, 4, 1 > Array4i
Definition: Array.h:344
Here is the initial vector v:
7 2 6 6
Here is the sorted vector v:
2 6 6 7

Similar to std::vector, 1D expressions also exposes the pair of cbegin()/cend() methods to conveniently get const iterators on non-const object.

Iterating over coefficients of 2D arrays and matrices

STL iterators are intrinsically designed to iterate over 1D structures. This is why begin()/end() methods are disabled for 2D expressions. Iterating over all coefficients of a 2D expressions is still easily accomplished by creating a 1D linear view through reshaped():

Example:Output:
cout << "Here are the coeffs of the 2x2 matrix A:\n";
for(auto x : A.reshaped())
cout << x << " ";
cout << "\n";
MatrixXcf A
Matrix< int, 2, 2 > Matrix2i
2×2 matrix of type int.
Definition: Matrix.h:500
Here are the coeffs of the 2x2 matrix A:
7 -2 6 6 

Iterating over rows or columns of 2D arrays and matrices

It is also possible to get iterators over rows or columns of 2D expressions. Those are available through the rowwise() and colwise() proxies. Here is an example sorting each row of a matrix:

Example:Output:
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";
RowXpr row(Index i)
This is the const version of row(). *‍/.
ConstRowwiseReturnType rowwise() const
Definition: DenseBase.h:548
Array< int, Dynamic, Dynamic > ArrayXXi
Definition: Array.h:344
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