vector<int> array2vector(int array[]) {
int l = sizeof(array) / sizeof(array[0]);
vector<int> result(array, array + l);
return result;
}
int main() {
int my_array[] = { 1,3,5,2,6 };
vector<int> baby = array2vector(my_array);
for (int i : baby) {
cout << i << endl;
}
return 0;
}
There have been many ways to convert an int array to a vector, but the examples always starts with initializing an int array, and then converting it into a vector. However, I'd like to know if a function takes in an int array, and I want to convert it into a vector within the function, how I should do it?
The above code has the problem that sizeof(array) is "Diving size of a pointer by another value". The code prints out
1
3
instead of the entire array.