Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 426
ajd. Avatar asked Apr 02 '11 00:04

ajd.


People also ask

How do you pass a vector array to a function in C++?

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.

How do you pass a vector reference in C++?

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.

How do you input an array into a vector?

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.


3 Answers

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.

like image 147
James McNellis Avatar answered Nov 15 '22 00:11

James McNellis


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.

like image 42
Matteo Italia Avatar answered Nov 14 '22 23:11

Matteo Italia


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.

like image 31
ryaner Avatar answered Nov 14 '22 23:11

ryaner