将std::vector<int>转换为arma::rowvec

3

我有一个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");

但是我得到了:
error: Mat::operator(): out of bounds

terminate called after throwing an instance of 'std::logic_error'
  what():  

如果我在最后的rowvec中使用 a << *iter2; 而不是 a(j++,0) = *iter2;,我只得到了最后一个元素。

4个回答

10

最近版本的Armadillo能够直接从std::vector实例构建矩阵/向量对象。

例如:

std::vector<double> X(5);

// ... process X ...

arma::vec Y(X);
arma::mat M(X);

9

您忘记设置行向量的大小。

更正确的代码应该是:

vector<int> x = foo();
rowvec a(x.size());
... rest of your code ...

通过 conv_to 函数,也可以将 std::vector 转换为 Armadillo 矩阵或向量。因此,不需要手动循环,可以这样做:

vector<int> x = foo();
rowvec a = conv_to<rowvec>::from(x);

请注意,rowvecRow<double> 的同义词。请参阅 Row 类的文档。因此,在两个代码示例中都存在 intdouble 的转换。如果您不希望这样做,可以考虑使用 irowvec

2
使用带有aux_mem指针的构造函数?
 rowvec a(x.pointer, x.size()); 

这个告诉我: 无效使用std::vector<int, std::allocator<int> >::pointer - nkint

0

尝试类似这样的东西

vector<int> x = foo();
vector<int>::const_iterator iter2;
stringstream buffer;
for(iter2 = x.begin(); iter2 != x.end(); ++iter2) 
{
   buffer  << *iter << " ";    
}
// To remove the extra trailing space, not sure if it is needed or not
string elements = buffer.str().substr(0,buffer.str().length()-1);

rowvec a = rowvec(elements.c_str());

根据 Armadillo文档,rowvec的构造器可以使用arma :: rowvec、arma :: mat、字符串(读取const char *)或初始值列表作为参数,如果您使用C++11。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接