Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

c++ - Can I call functions that take an array/pointer argument using a std::vector instead?

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);

so currently I have code of the form

 unsigned char* pArray = new unsigned char[iSize];
 //   populate array with data
 WriteToSocketBuffer(pArray,iSize);
 delete [] pArray;

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, The elements of a vector are assured to be contiguous similar to an array.

Reference:

C++03 Standard: [lib.vector] 23.2.4 Class template vector

......
The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...