Initializing a vector with part of an array?

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

usually we do:

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

but how to initialize the vec vector with only the first three values ​​of arr ? Also how to initialize it with averages of 3?

I need to initialize it right away, and not push_backon multiple lines.

+3
source share
1 answer

The constructor form you invoke is ** :

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

So, you can pass everything that acts as a pair of iterators. In particular, you can pass two pointers if they both point to the same array, and until the second comes before the first (if the pointers are equal, they represent an empty range).

() elment-after-the-last-element :

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

, .

vec arr?

:

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

3?

, , - . 1 4:

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


** , , , . : template <class InputIterator> vector( InputIterator first, InputIterator last, const Allocator& alloc = Allocator() );
+15

All Articles