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?

lukai
  • 536
  • 1
  • 5
  • 20
  • possible duplicate of [Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not?](http://stackoverflow.com/questions/988158/take-the-address-of-a-one-past-the-end-array-element-via-subscript-legal-by-the) – Pradhan Sep 13 '14 at 04:15

4 Answers4

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.

JDługosz
  • 5,592
  • 3
  • 24
  • 45
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].

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;

Rustam
  • 6,485
  • 1
  • 25
  • 25
0

vectorx(a,&a[3])

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

Rustam
  • 6,485
  • 1
  • 25
  • 25