使用std :: begin(),std :: end()将ArrayXd转换为stl向量, [英] Use std::begin(), std::end() to convert ArrayXd to stl vector,
问题描述
在我看来,我应该能够使用 std :: begin()
和 std :: end()
将 ArrayXd
转换为 std :: vector< double>
;但是,当我在以下代码中尝试时,我的尝试失败了。我的理解是,任何 Eigen
对象上的 .data()
方法都返回一个指向连续内存块的指针,类似于c样式数组。因此,由于我可以在ac样式数组上使用 std :: begin()
, std :: end()
,我希望它也可以与 .data()
一起使用。但是,Eigen类是模板化的,我认为这是导致我遇到问题的原因,但没有找到解决此问题的方法。
It seems to me that I should be able to use std::begin()
and std::end()
to convert ArrayXd
to std::vector<double>
; however, when I tried it in the following code, my attempt failed. My understanding is that .data()
method on any Eigen
object returns a pointer to a continuous block of memory similar to c style array. Therefore, since I can use std::begin()
, std::end()
on a c style array, I expected that to work with .data()
as well. However, Eigen classes are templated, and I think this is what causes me problems, but don't see a way to fix this. How should this be done?
#include <iostream>
#include <vector>
#include <Eigen/Dense>
using namespace Eigen;
int main()
{
ArrayXd e_array(5);
e_array << 3,4,5,6,7;
double c_array[] = {1,2,3,4,5};
//Fails
// std::vector<double> my_vec(std::begin(e_array.data()), std::end(e_array.data()));
// Works
// std::vector<double> my_vec(e_array.data(), e_array.data() + 5);
// Works
// std::vector<double> my_vec(std::begin(c_array), std::end(c_array));
// Works
// std::vector<double> my_vec(c_array, c_array + 5);
return 0;
}
我的错误消息(第一行,整个消息很长):
My error message(First lines, the whole message is long):
错误:没有匹配函数调用
'begin(Eigen :: PlainObjectBase> :: Scalar *)'
std :: vector my_vec(std :: begin(e_array.data()),
std :: end(e_array.data()))
error: no matching function for call to ‘begin(Eigen::PlainObjectBase >::Scalar*)’ std::vector my_vec(std::begin(e_array.data()), std::end(e_array.data()))
推荐答案
std :: begin(vec.data())
无法工作,因为data()返回原始数据无法传达向量中元素数量的指针。此版本是您最好的版本:
std::begin(vec.data())
cannot work because data() returns a raw pointer which cannot convey the number of elements in the vector. This version is the best one of yours:
std::vector<double> my_vec(e_array.data(), e_array.data() + 5);
稍好一点:
std::vector<double> my_vec(e_array.data(), e_array.data() + e_array.size());
您也许还可以使用许多容器来做到这一点,但特别是使用Eigen的ArrayXd,因为它缺少 begin()
和 end()
(相关: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=231 )。
And you may also be able to do this with many containers, but not with Eigen's ArrayXd in particular, because it lacks begin()
and end()
(related: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=231).
std::vector<double> my_vec(foo.begin(), foo.end());
这篇关于使用std :: begin(),std :: end()将ArrayXd转换为stl向量,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!