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!

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

But be careful with zero size arrays.
What if vector gets relocated?
@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.
Be reminded that this only works for std::vector<T> with T!=bool as std::vector<bool> is a special case, where 8 bools are squeezed into one byte.
@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<int>'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<int>. Usually it's better to replace nested vectors with a single vector, but not always.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.