gpt4 book ai didi

c++ - 如何将 STL vector 传递给采用 const [] 的函数 (c++)

转载 作者:太空狗 更新时间:2023-10-29 23:31:49 25 4
gpt4 key购买 nike

我有一个 3d STL vector ,

vector<vector<vector<double> > > mdata;

我还有一个功能

myfun(const double ya[]);

更准确地说,它是 GNU 科学图书馆的一个函数,

gsl_spline_init(gsl_spline * spline, const double xa[], const double ya[], size_t size);

但这与我的问题无关。

所以现在我想将数据的“最后”维度传递给 myfun。我一直在尝试这个:

for (int s = 0; s < msize; s++) {
accelerators = new gsl_interp_accel*[msize];
splines = new gsl_spline*[msize];
for (int i = 0; i < msize; i++) {
accelerators[i] = gsl_interp_accel_alloc();
splines[i] = gsl_spline_alloc(gsl_interp_cspline_periodic, msize+1);
gsl_spline_init(splines[i], &(*mgrid.begin()), &(*mdata[s][i].begin()), msize+1);
}
}

但是编译器(g++、64 位、Ubuntu)提示:

In member function ‘std::vector<std::vector<std::vector<double,
std::allocator<double> >,
std::allocator<std::vector<double,
std::allocator<double> > > >,
std::allocator<std::vector<std::vector<double,
std::allocator<double> >,
std::allocator<std::vector<double,
std::allocator<double> > > > > >
SimpleAmfCalculator::interp_m(int)
’: Calculator.cpp:100: error: cannot convert ‘std::vector<double,
std::allocator<double> >*
’ to ‘const
double*
’ for argument ‘3’ to ‘int
gsl_spline_init(gsl_spline*, const
double*, const double*, size_t)
’ make: *** [Calculator.o] Error 1

非常感谢任何帮助!

最佳答案

您可以传递第一个元素的地址,例如:

#include <vector>

void fun(const double data[])
{

}

int main()
{
std::vector<std::vector<std::vector<double> > > data3d;
....
fun(&data3d[0][0][0]);
}

vector 的元素是连续存储的。所以我希望这种方式是标准的:)

23.2.4 Class template vector

1 A vector is a kind of sequence that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity:

&v[n] == &v[0] + n for
all 0 <= n < v.size().

关于c++ - 如何将 STL vector 传递给采用 const [] 的函数 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1329415/

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