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():  

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

4

4 回答 4

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

于 2012-02-15T09:29:43.487 回答
9

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

例如:

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

// ... process X ...

arma::vec Y(X);
arma::mat M(X);
于 2013-08-13T11:52:05.403 回答
2

使用带有 aux_mem 指针的构造函数?

 rowvec a(x.pointer, x.size()); 
于 2012-02-14T13:50:46.460 回答
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)。

于 2012-02-14T13:40:32.670 回答