将vector作为参数传递

来源:互联网 发布:淘宝换类目影响权重不 编辑:程序博客网 时间:2024/05/17 02:08

这两天在用c++写数值计算,手残选了个蛋疼的Boost库。boost的好处在于通用性,缺点……原型实在是太长了,make一下只要出一个error就被刷屏了(偶17寸屏幕18号字,谁让我是瞎子)。

首先简单介绍一下boost::numeric::ublas。

vector对象有vector<T>;切片(用过matlab的都懂,不懂你就out了)vector_range<vector<T> >, vector_slice<vector<T> >.

matrix对象有matrix<T,F,A>,官方解释如下点击打开链接http://www.boost.org/doc/libs/1_55_0/libs/numeric/ublas/doc/matrix.htm#matrix_

ParameterDescriptionDefaultTThe type of object stored in the matrix. FFunctor describing the storage organization. [1]row_majorAThe type of the Storage array. [2]unbounded_array<T>

此外还有matrix_row<...>,matrix_column<...>等等不再赘述。

上回折腾boost::bindings::lapack (肯定不是这个路径,大意如此)的时候就是,只要解线性系统就需要用matrix<T,column_major>来声明矩阵,亲测用"row_major"(就是默认的那个)不好使。这些都是题外话。

这回我用到向量场(函数),原型vector<double> Fooo(vector<double>) ,Fooo就是那个函数名(老外都喜欢用Foo,我就就就是想不通为什么)。按我的理解就是用vector当参数的时候尽量使用引用或者指针,所以应该是这样的 vector<double> Fooo(vector<double>&)!XXX,编译就是不过!调用的时候用的是Fooo(row(A,i)); 这里A是一个矩阵。这不坑爹呢么!用row()都能初始化vector!为什么不能当作vector参数!!!错误信息:

error: invalid initialization of non-const reference of type 'vec& {aka boost::numeric::ublas::vector<double>&}' from an rvalue of type 'boost::enable_if_c<true, boost::numeric::ublas::vector_binary_scalar1<const int, boost::numeric::ublas::vector<double>, boost::numeric::ublas::scalar_multiplies<int, double> > >::type {aka boost::numeric::ublas::vector_binary_scalar1<const int, boost::numeric::ublas::vector<double>, boost::numeric::ublas::scalar_multiplies<int, double> >}'

(想像一下,是不是一个错误就可以刷屏!)

解决办法1:函数声明为vector<> Fooo(vector<>)就好了(说好的效率呢?)

解决办法2:函数声明为vector<> Fooo(const vector<>&) 将参数用"const classname &"也就是传说中的“const referrence”传进去就好了。(其实人家错误信息里提示得很明显)

原理与左值和右值有关。貌似右值引用必须使用const reference,好像是《c++Primer》里的原话(!T^T!当初好好学学扎实点现在就不用这么费劲了),不过幸运的是我一下就猜到了要使用const reference(哈哈哈哈我真是太机智了)问题迎刃而解。


尾声

1.尼玛六一儿童节不让我过我就忍了;端午可以是全国放假啊!凭什么我还得码码码码代码!

2.珍爱生命;matlab真心好用!

3.用c++做数值的话强烈推荐Eigen或者Armadillo,虽然不到万不得已我还是喜欢用boost!(绝对是脑残)

3.我还是太年轻了。


来个图秀一下脑残


这图我用gnuplot搞的敢说?


接着码罢。

0 0
原创粉丝点击