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.
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: |
---|---|
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 |
One dimensional expressions can also easily be passed to STL algorithms:
Similar to std::vector
, 1D expressions also exposes the pair of cbegin()/cend()
methods to conveniently get const iterators on non-const object.
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()
:
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:
© Eigen.
Licensed under the MPL2 License.
https://eigen.tuxfamily.org/dox/group__TutorialSTL.html