How to create a nonempty boost ublas::vector inside an initializer list?

馋奶兔 提交于 2019-12-13 04:44:59

问题


I'm trying to do something like this

#include <boost/numeric/ublas/vector.hpp>
using namespace boost::numeric::ublas;

class A{
 protected:
    vector< double > a_;
 public:
    A( vector< double > a ) :
        a_( a ) {};
};

class B : public A{
 public:
    B() : A( vector< double >( { 1.25, 2.75, 3.34 } ) ){};
};

The result should be, that the vector a_ gets declared as a three-vector containing a_[0]=1.25, a_[1]=2.75, a_[2]=3.34.

This code is not working because boost::numeric::ublas::vector does not have a constructor which can handle vector<double>( { 1.25, 2.75, 3.34 } )

What should I use instead? Maybe the constructor

vector (size_type size, const double &data)

from the boost documentation helps?


回答1:


You may change the default storage type of an ublas/vector from unbounded_array to std::vector to get initializer_list support or introduce a helper function to initialize the member:

#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
using namespace boost::numeric::ublas;

template <typename T>
unbounded_array<T> make_unbounded_array(std::initializer_list<T> list) {
    unbounded_array<T> result(list.size());
    for(unsigned i = 0; i < list.size(); ++ i)
        result[i] = *(list.begin() + i);
    return result;
}

class Example
{
    public:
    vector<double, std::vector<double>> v0;
    vector<double> v1;

    public:
    Example()
    :   v0({ 1.25, 2.75, 3.34 }),
        v1(make_unbounded_array({ 1.25, 2.75, 3.34 }))
    {}
};


int main(int argc, char **argv) {
    Example example;
    std::cout
        << example.v0[0] << " == " << example.v1[0] << '\n'
        << example.v0[1] << " == " << example.v1[1] << '\n'
        << example.v0[2] << " == " << example.v1[2] << '\n'
    ;
}


来源:https://stackoverflow.com/questions/27459318/how-to-create-a-nonempty-boost-ublasvector-inside-an-initializer-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!