Reputation: 566
we can initialize a vector using array. suppose,
int a[]={1,2,3}
vector<int>x(a,a+3)
this is a way . My question is, what is a
and a+3
here, are they pointer?
and someone could explain this: for the above array
vector<int>x(a,&a[3])
also gives no error and do the same as above code. If we write a[3], it should be outside of the array? can someone tell me the inner mechanism?
Upvotes: 0
Views: 84
Reputation: 6515
int a[]={1,2,3}
vectorx(a,a+3)
a is an array so it is always pointing to its base address. a+3 mean base address+(sizeof(int) *3)
suppose base address is 100 a=100; a+3=106;
Upvotes: 0
Reputation: 5642
Yes, a
and a+3
are pointers. The plain a
is an array that gets converted implicitly to a pointer at the drop of a hat.
The construct &a[3]
is identical in meaning to a+3
for plain C arrays. Yes, a[3]
is outside the array, but one-past is allowed to point to, if you don't dereference it.
Upvotes: 3
Reputation:
A vector's range constructor looks like this:
template <class InputIterator>
vector (InputIterator first, InputIterator last,
const allocator_type& alloc = allocator_type());
It will construct elements in the range [first, last)
, meaning that the last element is not included. &a[3]
points to an element outside the bounds of the array, similar to how std::end(a)
will point one past the end of a
. Compare it to:
std::vector<int> x(std::begin(a), std::end(a));
Also, *(a + 3)
is equivalent to a[3]
.
Upvotes: 0