filling a boost vector or matrix

Mr Fooz picture Mr Fooz · Apr 28, 2009 · Viewed 17k times · Source

Is there a single-expression way to assign a scalar to all elements of a boost matrix or vector? I'm trying to find a more compact way of representing:

boost::numeric::ublas::c_vector<float, N> v;
for (size_t i=0; i<N; i++) {
    v[i] = myScalar;
 }

The following do not work:

boost::numeric::ublas::c_vector<float, N> 
   v(myScalar, myScalar, ...and so on..., myScalar);

boost::numeric::ublas::c_vector<float, N> v;
v = myScalar;

Answer

user21714 picture user21714 · Apr 28, 2009

Because the vector models a standard random access container you should be able to use the standard STL algorithms. Something like:

c_vector<float,N> vec;
std::fill_n(vec.begin(),N,0.0f);

or

std::fill(vec.begin(),vec.end(),0.0f);

It probably also is compatible with Boost.Assign but you'd have to check.