简体   繁体   中英

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 };

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.)

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM