module
Using STL Containers with EigenContents
Executive summary
Using STL containers on fixed-size vectorizable Eigen types, or classes having members of such types, requires taking the following two steps:
- A 16-byte-aligned allocator must be used. Eigen does provide one ready for use: aligned_
allocator. - If you want to use the std::vector container, you need to #include <Eigen/StdVector>.
These issues arise only with fixed-size vectorizable Eigen types and structures having such Eigen objects as member. For other Eigen types, such as Vector3f or MatrixXd, no special care is needed when using STL containers.
Using an aligned allocator
STL containers take an optional template parameter, the allocator type. When using STL containers on fixed-size vectorizable Eigen types, you need tell the container to use an allocator that will always allocate memory at 16-byte-aligned locations. Fortunately, Eigen does provide such an allocator: Eigen::
For example, instead of std::map<int, Eigen::Vector4f>
you need to use
std::map<int, Eigen::Vector4f, std::less<int>, Eigen::aligned_allocator<std::pair<const int, Eigen::Vector4f> > >
Note that the third parameter "std::less<int>" is just the default value, but we have to include it because we want to specify the fourth parameter, which is the allocator type.
The case of std::vector
The situation with std::vector was even worse (explanation below) so we had to specialize it for the Eigen::
Here is an example:
#include<Eigen/StdVector> /* ... */ std::vector<Eigen::Vector4f,Eigen::aligned_allocator<Eigen::Vector4f> >
An alternative - specializing std::vector for Eigen types
As an alternative to the recommended approach described above, you have the option to specialize std::vector for Eigen types requiring alignment. The advantage is that you won't need to declare std::vector all over with Eigen::allocator. One drawback on the other hand side is that the specialization needs to be defined before all code pieces in which e.g. std::vector<Vector2d> is used. Otherwise, without knowing the specialization the compiler will compile that particular instance with the default std::allocator and you program is most likely to crash.
Here is an example:
#include<Eigen/StdVector> /* ... */ EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Matrix2d) std::vector<Eigen::Vector2d>
Explanation: The resize() method of std::vector takes a value_type argument (defaulting to value_type()). So with std::vector<Eigen::Vector4f>, some Eigen::