关于Eigen中Map
以下内容大部分来之Eigen官网地址为:
http://eigen.tuxfamily.org/dox/classEigen_1_1Map.html
首先我们看Eigen::Map原型
template<typename PlainObjectType, int MapOptions, typename StrideType>
class Map: public MapBase<Map<PlainObjectType, MapOptions, StrideType> >
PlainObjectType :映射数据的等价矩阵类型
MapOptions:指定指针对齐方式,默认是未对齐的
StrideType:指定步长
这个类的作用就是让非Eigen数据结构变成Eigenj矩阵或者向量时,减少在复制过程中的开销,Eigen官网说没有开销。
构造函数有以下
Map (PointerArgType dataPtr, const StrideType &stride=StrideType())
Map (PointerArgType dataPtr, Index size, const StrideType &stride=StrideType())
Map (PointerArgType dataPtr, Index rows, Index cols, const StrideType &stride=StrideType())
int array[9];
for (int i = 0; i < 9; ++i)
array[i] = i;
std::cout << Eigen::Map<Eigen::Matrix3i>(array) << std::endl;
输出:
0 3 6
1 4 7
2 5 8
我们可以指定转换成矩阵或向量时的规则,使用模板参数StrideType比如
int array[12];
for(int i = 0; i < 12; ++i) array[i] = i;
cout << Map<VectorXi, 0, InnerStride<2> >
(array, 6) // the inner stride has already been passed as template parameter
<< endl;
输出:
0
2
4
6
8
10
除此之外我们还可以指定外部规则,比如可以指定矩阵每列的指针差值
int array[12];
for(int i = 0; i < 12; ++i) array[i] = i;
cout << Map<MatrixXi, 0, OuterStride<> >(array, 3, 3, OuterStride<>(4)) << endl;
输出:
0 4 8
1 5 9
2 6 10
上面的映射规则一般用的很少,比较常见的时用来将一个数组元素转换成Eigen数据结构
int data[] = {1,2,3,4,5,6,7,8,9};
Map<RowVectorXi> v(data,4);
cout << "The mapped vector v is: " << v << "\n";
new (&v) Map<RowVectorXi>(data+4,5);
cout << "Now v is: " << v << "\n";
Output:
The mapped vector v is: 1 2 3 4
Now v is: 5 6 7 8 9