23

I have a library which expects a array and fills it. I would like to use a std::vector instead of using an array. So instead of

int array[256];
object->getArray(array);

I would like to do:

std::vector<int> array;
object->getArray(array);

But I can't find a way to do it. Is there any chance to use std::vector for this?

Thanks for reading!


EDIT: I want to place an update to this problem: I was playing around with C++11 and found a better approach. The new solution is to use the function std::vector.data() to get the pointer to the first element. So we can do the following:

std::vector<int> theVec;
object->getArray(theVec.data()); //theVec.data() will pass the pointer to the first element

If we want to use a vector with a fixed amount of elements we better use the new datatype std::array instead (btw, for this reason the variable name "array", which was used in the question above should not be used anymore!!).

std::array<int, 10> arr; //an array of 10 integer elements
arr.assign(1); //set value '1' for every element
object->getArray(arr.data());

Both code variants will work properly in Visual C++ 2010. Remember: this is C++11 Code so you will need a compiler which supports the features!

The answer below is still valid if you do not use C++11!

SideEffect
  • 401
  • 3
  • 5
  • 10

1 Answers1

28

Yes:

std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer

Elements in a vector are guaranteed to be contiguous, like an array.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 5
    But be careful with zero size arrays. – Yakov Galka Sep 24 '10 at 12:42
  • What if vector gets relocated? – alxx Sep 24 '10 at 12:44
  • @alxx: How can it be reallocated from within `getArray`? I assume that's what you mean, since it's not a problem outside of it. – GManNickG Sep 24 '10 at 12:48
  • 2
    @alxx: if reallocated, as if `array` was reseated (in the event it's not allocated on the stack) then the pointer would now be invalid. @GMan: I would suggest passing the size, even though it's absent from the original question. – Matthieu M. Sep 24 '10 at 12:55
  • 10
    Be reminded that this only works for std::vector with T!=bool as std::vector is a special case, where 8 bools are squeezed into one byte. – fschmitt Sep 24 '10 at 13:29
  • @GManNickG: what if we have a `vector>`?? – Manolete Oct 18 '12 at 12:08
  • Can we get all the data contiguously in an array? – Manolete Oct 18 '12 at 15:46
  • 2
    @Manolete: You can get the inner vector's pointer to it's array of int's, and you can get the outer vector's pointer to it's array of `vector`'s, but there's no way to get a contiguous array of every single `int`, because that's not what that container says it is. That would be `vector`. *Usually* it's better to replace nested vectors with a single vector, but not always. – GManNickG Oct 18 '12 at 15:54