zzanzzani
zzanzzani

Reputation: 11

c++ vector and sizeof

This is my first time studying vector in C++. In the code below, I don't understand why the output of the array "sixth" is { 16, 2, 77, 29 }. I think the output should be { 20, 6, 81, 33 }.

int myints[] = { 16, 2, 77, 29 };

std::vector<int> sixth(myints, myints + sizeof(myints) / sizeof(int));

for (std::vector<int>::iterator it = sixth.begin(); it != sixth.end(); ++it)
    std::cout << "  " << *it;

output: 16, 2, 77, 29

My calculation:

std::vector sixth (4, myints + 16 / 4 );
sixth = { myints[0] + 16 / 4, myints[1] + 16 / 4, myints[2] + 16 / 4, myints[3] + 16 / 4 };
sixth = { 16 + 4, 2 + 4, 77 + 4, 29 + 4 };
sixth = { 20, 6, 81, 33 };

Upvotes: 1

Views: 132

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

You have misunderstood the arguments completely.
They are iterators - which are pointers, in this case - not "number of elements" and "operation to perform on the elements".

std::vector<int> sixth (myints, myints + sizeof(myints) / sizeof(int));

is the same as

int* begin = &myints[0]; // Pointer to the first array element
int* end = &myints[4];   // Pointer "one past" the last array element
std::vector<int> sixth (begin, end);

and just copies the array elements between begin and end into the vector.
(This is a very common interface in the standard library. You will see plenty of it. )

(Side note: I think that if you're not familiar with the implicit conversions from arrays to pointers, and the nature of pointer arithmetic, your interpretation makes just as much sense as this.)

Upvotes: 4

Refugnic Eternium
Refugnic Eternium

Reputation: 4291

It is behaving exactly as it should.

You are not performing and sort of mathematical operation, but much rather the line std::vector<int> sixth (myints, myints + sizeof(myints) / sizeof(int) ); merely tells your vector where to get it's values from.

It's the same as if you'd write:

for (int i = 0; i < sizeof(myints) / sizeof(int); ++i)
  sixth.push_back(myints[i]);

What you are doing in that line is calculate the 'end position of the source array' and the return value is a pointer to 'at the end of the array'.

Upvotes: 1

Related Questions