0

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?

1

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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;

Comments

0

vectorx(a,&a[3])

Here &a[3] is equivalent to a+3

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.