3
int arr[5] = {0,1,2,3,4};
vector<int> vec;

normally we do:

vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));

but how do initialize a vector vec with only first 3 values of arr? Also how do I initialize it with the middle 3 values?

I have to initialize it right away, no push_back on multiple lines..

1 Answer 1

15

The constructor form you are invoking is this**:

template <class Iterator> vector(Iterator start, Iterator end);

So, you may pass in anything that acts like a pair of iterators. Specifically, you may pass in two pointers, as long as they both point into the same array, and as long as the 2nd doesn't come before the first (if the pointers are equal, they represent an empty range).

In your example, you pass in a pointer to the first element of the array and a pointer to the (mythical) elment-after-the-last-element of the array:

vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));

Generally, you may pass in a pointer to any element as the start, and a pointer past any element as the finish.

but how do I initialize a vector vec with only first 3 values of arr?

Pass in pointers to the first and one past the third elements:

vector<int> vec(arr, arr+3);

Also how do I initialize it with middle 3 values?

Pass in a pointer to the first item you want to copy, and a pointer to one paste the final element. In this case, indexes 1 and 4:

vector<int> vec(arr+1, arr+4);


** Okay, it is slightly more complicated than that, but it's okay to pretend for the sake of this discussion. The actual form is: template <class InputIterator> vector( InputIterator first, InputIterator last, const Allocator& alloc = Allocator() );

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

1 Comment

Minor nitpick: you wrote [..] as long as the 2nd comes after the first. I think this is imprecise - the two given pointers can actually be equal. This would be an empty range.

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.