arma::rowvec from std::vector<int>

11,326

Solution 1

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);

Solution 2

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.

Solution 3

Using the constructor that takes an aux_mem pointer?

 rowvec a(x.pointer, x.size()); 
Share:
11,326
nkint
Author by

nkint

recursive: adjective, see recursive.

Updated on June 04, 2022

Comments

  • nkint
    nkint about 2 years

    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.

  • nkint
    nkint over 12 years
    this say me: ‘invalid use of std::vector<int, std::allocator<int> >::pointer’