如何在初始化列表内创建一个非空的boost ublas :: vector? [英] How to create a nonempty boost ublas::vector inside an initializer list?

查看:82
本文介绍了如何在初始化列表内创建一个非空的boost ublas :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做这样的事情

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

结果应该是向量a_被声明为包含a_[0]=1.25, a_[1]=2.75, a_[2]=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.

此代码不起作用,因为boost::numeric::ublas::vector没有可处理vector<double>( { 1.25, 2.75, 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)

来自加强文档 a>有帮助吗?

推荐答案

您可以将ublas/vector的默认存储类型从unbounded_array更改为std :: vector以获得initializer_list支持或引入帮助器函数来初始化成员:

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'
    ;
}

这篇关于如何在初始化列表内创建一个非空的boost ublas :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆