将 std::vector 作为 const float * 传递?
Pass std::vector as const float *?
我的函数是:
void function(const float *, int sizeOfArray){...}
我的向量是:
std::vector<float> myVector(size, val);
我在文档中读到您可以使用 myVector[0] 作为标准的 C++ 静态数组操作。
如何将该向量传递给该函数而不必将值复制到新的动态数组? (我想避免为此使用 new / delete)。
是不是有点像...?
function(myVector[0], size);
顺便说一句,我正在使用 C++11。
function(myVector.data(), myVector.size());
您可以使用 std::vector::data (C++11 起)获取指向底层数组的指针。
Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty (data() is not dereferenceable in that case).
例如
function(myVector.data(), myVector.size());
Is it something like...?
function(myVector[0], size);
myVector[0]
将 return 元素(即 float&
),而不是地址(即 float*
)。在 C++11 之前你可以通过 &myVector[0]
.
我的函数是:
void function(const float *, int sizeOfArray){...}
我的向量是:
std::vector<float> myVector(size, val);
我在文档中读到您可以使用 myVector[0] 作为标准的 C++ 静态数组操作。
如何将该向量传递给该函数而不必将值复制到新的动态数组? (我想避免为此使用 new / delete)。
是不是有点像...?
function(myVector[0], size);
顺便说一句,我正在使用 C++11。
function(myVector.data(), myVector.size());
您可以使用 std::vector::data (C++11 起)获取指向底层数组的指针。
Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty (data() is not dereferenceable in that case).
例如
function(myVector.data(), myVector.size());
Is it something like...?
function(myVector[0], size);
myVector[0]
将 return 元素(即 float&
),而不是地址(即 float*
)。在 C++11 之前你可以通过 &myVector[0]
.