gpt4 book ai didi

c++ - 如何在初始化列表中创建一个非空的 boost ublas::vector?

转载 作者:行者123 更新时间:2023-11-28 06:31:25 26 4
gpt4 key购买 nike

我正在尝试做这样的事情

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

结果应该是 vector a_被声明为包含 a_[0]=1.25, a_[1]=2.75, a_[2]=3.34 的三 vector .

此代码无效,因为 boost::numeric::ublas::vector没有可以处理 vector<double>( { 1.25, 2.75, 3.34 } ) 的构造函数

我应该改用什么?也许是构造函数

vector (size_type size, const double &data)

来自 boost documentation有帮助吗?

最佳答案

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

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

关于c++ - 如何在初始化列表中创建一个非空的 boost ublas::vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27459318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com