Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Initialize STL Vector with Array

📅 2010-Feb-03 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ arrays, cpp, stl, vector ⬩ 📚 Archive

A STL vector does not have any constructor that looks like it accepts an array. So, the straightforward way to initialize a vector with an array looks like:

#include <vector>

int arr[ARR_LEN] = { /* Array elements */ };
std::vector iVec;
for (int i = 0; i < ARR_LEN; ++i)
    iVec.push_back( arr[i] );

That is too much code for a simple initialization! Thankfully, there is another way do it with less code.

The constructor vector(InputIterator begin, InputIterator end) which initializes a vector with the elements of the range [begin, end) can be used with arrays too. This is because array pointers have all the properties required of an (input) iterator:

#include <vector>

int arr[ARR_LEN] = { /* Array elements */ };
std::vector<int> iVec(arr, arr + ARR_LEN);

Note that the second argument arr + ARR_LEN is beyond the last element of the array and thus behaves as the correct end().


© 2023 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧