-2

Discussion about std::vector and standard array

Say if we have following code:

void myclass::loadArray(void *outData)
void myclass::loadVector(void *outData)


void myclass::func ()
{
//here we have a vector
std::vector<int> myVector;
myVector.resize(10)

// here we have an array
int myArray[10];

here I wonder what will be the differences between following implementations //1: array myclass::loadArray(myArray)

//2: array 
myclass::loadArray(&(myArray[0]))


//1: vector
myclass::loadVector(myVector)

//2: vector
myclass::loadVector(&(myVector[0]))


}

From my understanding, Just depending on if we want to use array and vector we pick different solution. There is no difference between 1 and 2. Could you please correct me if I am wrong.

1
  • What happened when you compiled and ran it?
    – Kerrek SB
    May 27, 2015 at 14:46

2 Answers 2

2

The two versions with the array are equivalent: in the first, the array is implicitly converted to a pointer to its first element, which the second creates explicitly.

The first version with the vector won't compile, since there is no implicit conversion to a pointer. You'll have to explictly get the address of the array; either as you do in the second version, or with vector.data().

0

1 and 2 will be the same for the array versions. In the first, the array will decay to a pointer to the first element, the second calls explicitly with a pointer to the first element.

The first vector version will not compile as you can't implicitly change a std::vector to a void*.

For the second vector version, you will be calling the function with a pointer to the first element stored in the vector, not the vector itself.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.