6

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!

ajd.
  • 631
  • 1
  • 6
  • 8
  • 2
    One of the design-goals of std::vector was that this example should work. – Sjoerd Apr 02 '11 at 00:42
  • 3
    In the new standard, there is even a `v.data()` member so you don't have to write `&v[0]` anymore: and what could be more clear than `add1(v.data(), v.size());` ! – Sjoerd Apr 02 '11 at 00:44
  • thanks all for for the answers and comments! – ajd. Apr 02 '11 at 01:00

4 Answers4

6

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
3

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
2

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.

Community
  • 1
  • 1
ryaner
  • 3,927
  • 4
  • 20
  • 23
0

This should work. I don't see any problem.

Sadique
  • 22,572
  • 7
  • 65
  • 91