我有一个std :: vector,我想将它转换为arma :: rowvec
我弄完了:
vector<int> x = foo();
rowvec a;
vector<int>::const_iterator iter2;
int j = 0;
for(iter2 = x.begin(); iter2 != x.end(); ++iter2) {
a(j++,0) = *iter2;
}
a.print("a");
Run Code Online (Sandbox Code Playgroud)
但我得到:
error: Mat::operator(): out of bounds
terminate called after throwing an instance of 'std::logic_error'
what():
Run Code Online (Sandbox Code Playgroud)
如果不是a(j++,0) = *iter2;我a << *iter2;在最后的rowvec中使用,我只得到最后一个元素.
小智 8
最新版本的Armadillo能够直接从std :: vector的实例构造矩阵/向量对象.
例如:
std::vector<double> X(5);
// ... process X ...
arma::vec Y(X);
arma::mat M(X);
Run Code Online (Sandbox Code Playgroud)
你忘了设置行向量的大小.
更正确的代码是:
vector<int> x = foo();
rowvec a(x.size());
... rest of your code ...
Run Code Online (Sandbox Code Playgroud)
也可以通过conv_to函数将std :: vector转换为Armadillo矩阵或向量 .因此,您可以执行以下操作,而不是手动循环:
vector<int> x = foo();
rowvec a = conv_to<rowvec>::from(x);
Run Code Online (Sandbox Code Playgroud)
请注意,rowvec是Row <double>的同义词.请参阅Row类的文档.因此,在两个代码示例中,还存在int到双重转换.如果您不想这样,您可能希望使用irowvec代替.