简体   繁体   中英

Why does the vector(begin, end) constructor work for this initialization?

I'm coming from Java, and I'm now trying to initialize a vector in C++. I found a good way from this guy's answer . However, I don't know why it works.

I looked up the documentation for the constructor summary of vector and found this: 屏幕截图

The last constructor is the one used in the the thread, and is shown here in my code:

#include "iostream"
#include "vector"

using namespace std;

int main()
{
    static const int arr[] = {1, 2, 3};
    vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0]));

    return 0;
}

How can it be that the new vector vec is initialized by copying the elements from "begin" to "end" if begin is just the c-array, and end is essentially the number of elements of the array, plus the memory allocated to arr . Maybe this documentation is too ambiguous, and this is really simple. Can someone at least point me to better documentation? Thanks.

arr[] is an array and arr is a pointer on the data contained in this array. Containers in the standard library use iterators to access data and these have been modeled after pointers so that's why the vector 's constructor can work with pointers as well.

Adding value to a pointer is called pointer arithmetic . Compiler knows the size of the object contained in the array so it automatically adds the right object size to pointer when incrementing. By default arr points to the first element of the array, arr + 1, to the second one, etc.

sizeof(arr[0]) is basically the size of the elements within the array. sizeof(arr) is the entire size in bytes of the array so in order to use pointer arithmetic, you need to know the number of element in the array so the iteration stops at the end. Since the array size is not defined as a constant in the code arr+sizeof(arr)/sizeof(arr[0]) is a way to calculate it.

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