我可以调用使用需要一个std ::向量不是数组/指针参数的功能呢? [英] Can I call functions that take an array/pointer argument using a std::vector instead?
问题描述
我想重写使用了大量的将unsigned char
阵列,而不是利用的std ::矢量&lt一些code; unsigned char型>
的对象。我的问题是,这些都是目前用于存储将被写入到一个串口或套接字写入缓冲区和库函数来做到这一点采取或者无效*
或无符号字符*
。这种函数的一个例子是
I want to rewrite some code that uses a lot of unsigned char
arrays, to instead make use of std::vector<unsigned char>
objects. The problem I have is that these are currently used to store the data that will be written to either a serial port or socket write buffer and the library functions to do this take either void*
or unsigned char*
. An example of such a function is
WriteToSocketBuffer(unsigned char* pBuffer, int iSize);
所以目前我有形式code
so currently I have code of the form
unsigned char* pArray = new unsigned char[iSize];
// populate array with data
WriteToSocketBuffer(pArray,iSize);
delete [] pArray;
我的问题是:如果我改变我的课有一个的std ::矢量&lt; unsigned char型&GT;
来代替原始的数组我可以简单地叫我的库函数使用
My question is the following: If I change my class to have a std::vector<unsigned char>
instead of a raw array can I simply call my library function using
std::vector<unsigned char> myVector;
WriteToSocketBuffer(&myVector[0],myVector.size());
是否通过第一元素的地址在同一载体行为是作为传递第一元件的地址在一个原始阵列。难道这个简单的?
Does passing the address of the first element in the vector act in the same was as passing in the address of the first element in a raw array. Is it this simple?
推荐答案
是的,一个向量的元素放心是连续类似于数组。
Yes, The elements of a vector are assured to be contiguous similar to an array.
参考:
C ++ 03标准: [lib.vector] 23.2.4类模板矢量
......结果
向量的元素被连续存储,这意味着如果 v
是矢量&lt; T,分配器&GT;
,其中 T
是某种类型的比布尔
,那么服从身份 &安培; v [N] ==&放大器; v [0] + N
所有 0℃; = N&LT; v.size()
......
The elements of a vector are stored contiguously, meaning that ifv
is avector<T, Allocator>
whereT
is some type other thanbool
, then it obeys the identity&v[n] == &v[0] + n
for all0 <= n < v.size()
这篇关于我可以调用使用需要一个std ::向量不是数组/指针参数的功能呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!