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 input 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!
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.
A vector<int> is not same as int[] (to the compiler). vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor. So, you must use vector<int>& (preferably with const , if function isn't modifying it) to pass it as a reference.
Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With