# 2. Map类型和Map变量声明

Map的定义：

``````Map<Matrix<typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime> >
``````

``````Map<MatrixXf> mf(pf,rows,columns);
``````

``````Map<const Vector4i> mi(pi);
``````

Map能够足够灵活地去容纳多种不同的数据表示，其他的两个模板参数：

``````Map<typename MatrixType,
int MapOptions,
typename StrideType>
``````
• MapOptions标识指针是否是对齐的（Aligned or Unaligned），默认是Unaligned。
• StrideType表示内存数组的组织方式：行列的步长。

``````int array[8];
for(int i = 0; i < 8; ++i) array[i] = i;
cout << "Column-major:\\n" << Map<Matrix<int,2,4> >(array) << endl;
cout << "Row-major:\\n" << Map<Matrix<int,2,4,RowMajor> >(array) << endl;
cout << "Row-major using stride:\\n" <<
Map<Matrix<int,2,4>, Unaligned, Stride<1,4> >(array) << endl;
``````

``````Column-major:
0 2 4 6
1 3 5 7
Row-major:
0 1 2 3
4 5 6 7
Row-major using stride:
0 1 2 3
4 5 6 7
``````

# 3. 使用Map变量

``````typedef Matrix<float,1,Dynamic> MatrixType;
typedef Map<MatrixType> MapType;
typedef Map<const MatrixType> MapTypeConst;   // a read-only map
const int n_dims = 5;

MatrixType m1(n_dims), m2(n_dims);
m1.setRandom();
m2.setRandom();
float *p = &m2(0);  // get the address storing the data for m2
MapType m2map(p,m2.size());   // m2map shares data with m2
MapTypeConst m2mapconst(p,m2.size());  // a read-only accessor for m2
cout << "m1: " << m1 << endl;
cout << "m2: " << m2 << endl;
cout << "Squared euclidean distance: " << (m1-m2).squaredNorm() << endl;
cout << "Squared euclidean distance, using map: " <<
(m1-m2map).squaredNorm() << endl;
m2map(3) = 7;   // this will change m2, since they share the same array
cout << "Updated m2: " << m2 << endl;
cout << "m2 coefficient 2, constant accessor: " << m2mapconst(2) << endl;
/* m2mapconst(2) = 5; */   // this yields a compile-time error
``````

``````m1:   0.68 -0.211  0.566  0.597  0.823
m2: -0.605  -0.33  0.536 -0.444  0.108
Squared euclidean distance: 3.26
Squared euclidean distance, using map: 3.26
Updated m2: -0.605  -0.33  0.536      7  0.108
m2 coefficient 2, constant accessor: 0.536
``````

Eigen提供的函数都兼容Map对象。

# 4. 修改Map数组

Map对象声明后，可以通过C++的`placement new`语法来改变Map的数组。

``````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";
``````

``````The mapped vector v is: 1 2 3 4
Now v is: 5 6 7 8 9
``````

``````Map<Matrix3f> A(NULL);  // don't try to use this matrix yet!
VectorXf b(n_matrices);
for (int i = 0; i < n_matrices; i++)
{
new (&A) Map<Matrix3f>(get_matrix_pointer(i));
b(i) = A.trace();
}
``````

“Eigen教程(8)”