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..
The constructor form you are invoking is this**:
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:
Generally, you may pass in a pointer to any element as the start, and a pointer past any element as the finish.
Pass in pointers to the first and one past the third elements:
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:
** 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() );