passing std::vector to a function which modifies an input array
I'm using a third-party API (CryptEncrypt, to be precise) which takes a C array as an in-out parameter. Logically, the API boils down to the following function:
void add1(int *inout, size_t length)
{
for(size_t i = 0; i < length; i++)
{
inout[i] += 1;
}
}
I'm trying to avoid the use of raw arrays, so my question is can I use the std::vector as an i开发者_运维问答nput to the API above? Something like the following:
#include <vector>
int main()
{
std::vector<int> v(10); // vector with 10 zeros
add1(&v[0], v.size()); // vector with 10 ones?
}
Can I use the 'contiguous storage' guarantee of a vector to write data to it? I'm inclined to believe that this is OK (it works with my compiler), but I'd feel a lot better if someone more knowledgeable than me can confirm if such usage doesn't violate the C++ standard guarantees. :)
Thanks in advance!
Can I use the 'contiguous storage' guarantee of a vector to write data to it?
Yes.
I'm inclined to believe that this is OK
Your inclination is correct.
Since it's guaranteed that the storage is contiguous (from the 2003 revision of the standard, and even before it was almost impossible to implement sensibly vector
without using an array under the hood), it should be ok.
Storage is guaranteed to be continuous by the standard but accessing element[0] on empty vector is undefined behaviour by the standard. Thus you may get error in some compilers. (See another post that shows this problem with Visual Studio 2010 in SO.)
The standard has resolved this in C++0x though.
This should work. I don't see any problem.
精彩评论