Reputation: 11733
I have an std::vector and I want to convert it into a arma::rowvec
I've done:
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");
but I get:
error: Mat::operator(): out of bounds
terminate called after throwing an instance of 'std::logic_error'
what():
If instead of a(j++,0) = *iter2;
I use a << *iter2;
in final rowvec, I get only the last element.
Upvotes: 3
Views: 12717
Reputation: 151
Recent versions of Armadillo are able to construct matrix/vector objects directly from instances of std::vector.
For example:
std::vector<double> X(5);
// ... process X ...
arma::vec Y(X);
arma::mat M(X);
Upvotes: 10
Reputation: 3620
You forgot to set the size of the row vector.
A more correct code would be:
vector<int> x = foo();
rowvec a(x.size());
... rest of your code ...
It's also possible to convert a std::vector to an Armadillo matrix or vector via the conv_to function. So instead of doing a manual loop, you can do this:
vector<int> x = foo();
rowvec a = conv_to<rowvec>::from(x);
Note that rowvec is a synonym for Row<double>. See the documentation for the Row class. As such, in both code examples there is also an int to double conversion occurring. If you don't want that, you may wish to use irowvec instead.
Upvotes: 9
Reputation: 9134
Using the constructor that takes an aux_mem pointer?
rowvec a(x.pointer, x.size());
Upvotes: 2
Reputation: 16076
Try something like
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());
As per the Armadillo Documentation rowvec's constructor will take a arma::rowvec, a arma::mat, a string (read const char*) or an initialiser list if you are using C++11.
Upvotes: 0