简体   繁体   中英

Uniform initialization with Eigen dynamic types

I'm trying to learn the Eigen C++ library, and was wondering if there is some nice shorthand for initializing dynamic vectors and matrices. It would be really nice to write something like you would using a std::vector

std::vector<int> myVec = {1,2,3,6,5,4,6};

ie

VectorXi x = {1,2,3,4,7,5,7};

The closest (ugly) equivalent I can find involves Map . .

int xc[] = {2,3,1,4,5};
Map<VectorXi> x(xc,sizeof(xc)/sizeof(xc[0]));

What other initialization methods are there?

For fixed size matrices/vectors, you can use the comma initializer:

Matrix3f m;
m<<1,2,3,4,5,6,7,8,9;

I can't test it right now, but it should work similarly for your situation:

VectorXi x(5);
x << 2,3,1,4,5;

If it does not, you could use a temporary Vector, fill it with the five elements using the comma initializer and then assign it to the VectorXi.

edit: You might also be interested in this page: Eigen: Advanced Initialization

By the code you showed, you are OK in writing const items. So maybe you can do something like

std::vector<int> vec;
const int init_vec[5] =  {1,2,3,4,5}
vec.assign(init_vec, init_vec + 5);

See this post of how use array to populate vectors.

EDIT: Correct a wrong link formating.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM